Looking to update the location of an element within a canvas using Vue and socket.io?

I am currently developing a 2D pong game using vue.js and socket.io. At the moment, I have a black rectangle displayed in a canvas. My goal is to make this rectangle move following the cursor of my mouse. The issue I am facing is that although my console logs show the correct coordinates, the position of the rectangle only updates when I refresh the page. (I also included buttons for moving the rectangle but they are not relevant in this case.)

Below is the code from my .vue file:

<template>
  <div>
    <canvas @mousemove="mouseMove" ref="game" width="640" height="480" style="border: 1px solid black;">

    </canvas>
    <p style = "display: flex; justify-content: space-around;">
        <button v-on:click="move('right')">Right</button>
        <button v-on:click="move('left')">Left</button>
        <button v-on:click="move('up')">Up</button>
        <button v-on:click="move('down')">Down</button>
    </p>
  </div>
</template>

<script>
    import io from "socket.io-client";
    export default {
        name: 'BlockGame',
        data() {
            return {
                socket: {},
                context: {},
                position: {
                    x: 0,
                    y: 0
                }
            }
        },
        created() {
            this.socket = io("http://localhost:3000");
        },
        mounted() {
            this.context = this.$refs.game.getContext("2d");
            this.socket.on("position", data => {
                this.position = data;

                console.log(data);
                
                this.context.clearRect(0, 0, this.$refs.game.width, this.$refs.game.height)
                console.log("mounted pos:" + this.position.x, this.position.y);
                this.context.fillRect(this.position.x, this.position.y, 20, 20);
            });
        },
        methods: {
            move(direction) {
                this.socket.emit("move", direction);
            },
            mouseMove() {
                this.socket.emit("mouseMove", event.clientX, event.clientY)
                console.log("event pos:" + event.clientX, event.clientY);
                console.log("position pos:" + this.position.x, this.position.y);
            }
        }
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

Additionally, here is the app.js code snippet:

const Express = require("express");
const Http = require("http").Server(Express);
const SocketIo = require("socket.io")(Http, {
    cors: {
      origin: "http://localhost:8080",
      methods: ["GET", "POST"]
    }
  });

var position = {
    x: 200,
    y: 200
}

SocketIo.on("connection", socket => {
    socket.emit("position", position)
    socket.on("move", data => {
        switch(data) {
            case "left":
                if (position.x - 5  < 0)
                    position.x = 0;
                else
                    position.x -= 5;
                SocketIo.emit("position", position);
                break;
            case "right":
                if (position.x + 5  >= 620)
                    position.x = 620;
                else
                    position.x += 5;
                SocketIo.emit("position", position);
                break;
            case "up":
                if (position.y - 5  < 0)
                    position.y = 0;
                else
                    position.y -= 5;
                SocketIo.emit("position", position);
                break;
            case "down":
                if (position.y + 5  >= 460)
                    position.y = 460;
                else
                    position.y += 5;
                SocketIo.emit("position", position);
                break;
        }
    })
    socket.on("mouseMove", (mousePosx, mousePosy) => {
        position.x = mousePosx;
        console.log("mousePosx:" + mousePosx)
        position.y = mousePosy;
        console.log("mousePosy:" + mousePosy)
        console.log("POSITIONposx:" + position.x)
        console.log("POSITIONposy:" + position.y)
    })
});

Http.listen(3000, () => {
    console.log("Listening at: 3000...");
})

Answer №1

After some investigation, I finally stumbled upon the solution buried within the lines of code. In order to properly transmit the position information to the Socket, make sure to include the following snippet:

        socket.on("mouseMove", (mousePosx, mousePosy) => {
        position.x = mousePosx;
        console.log("mousePosx:" + mousePosx)
        position.y = mousePosy;
        SocketIo.emit("position", position);
        console.log("mousePosy:" + mousePosy)
        console.log("POSITIONposx:" + position.x)
        console.log("POSITIONposy:" + position.y)
    })

An essential part of this process lies in

        SocketIo.emit("position", position);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensuring the script waits for the complete loading of iframe prior to

I'm faced with an issue on the website I'm currently working on. There's a Live Chat plugin integrated on an iframe, and I need to change an image if no agents are available. Interestingly, my code works perfectly fine when tested on the con ...

Parameter for Ajax URL

As a beginner in the world of Ajax, I'm on a mission to grasp the inner workings of this technology. I came across a tutorial on w3schools that sparked my curiosity. In the code snippet below, the 'url' is defined as demo_ajax_load.txt. Wil ...

designing various containers and adjusting their divisions

I have a pop-up window that contains the code snippet below, defining a template within a "container": <form method="post" class="signin" action="#"> <div id='container'> <div> <div id="divFeeTitle"&g ...

Tips for streamlining the JSON parse object prototype in JavaScript

I recently had a JavaScript object that was created without a prototype. let bar = Object.create(null); After reading and parsing a JSON file in Node.js, I reassigned the parsed data to bar. Here's how: fs.readFile('data.json', 'utf8 ...

Listening for Events from Child Components in Vue.js

I am struggling to figure out how to send an event from a child component to its parent in order to change the view. Although I have been able to create and emit the event, my template does not seem to be properly registering it. I am working with Single ...

Troubleshooting Next.js server actions with ESLint error detection

I encountered eslint errors while developing a basic server component with server action: // /app/search/page.tsx export default function Search() { async function updateResults(formData: FormData) { "use server"; await new Promise((r ...

To enable the standard PayPal 'donate' button functionality, you can remove the submitHandler from jQuery Validate dynamically

I need to insert a PayPal donate button into the middle of an AngularJS donation form, specifically by nesting the PayPal generated form tags within the donation form tags. This donation form is utilizing an older version (1.12) of jQuery Validate, which ...

Create a time of 00:19:59 using JavaScript

I am attempting to display a countdown timer that starts at 20 minutes in the format (00:20:00) using setInterval. Once the countdown is finished, it should display as (00:00:00), but I am having trouble achieving this. <body onload = "onloadFunc();" ...

Discovering when the DOM has finished rendering in AngularJS with ng-repeat

I am looking for a way to trigger an alert or message upon completion of rendering in my HTML DOM using AngularJS, specifically when dealing with multiple ng-repeats. HTML Code: <body> <div ng-controller="Ctrl"> <div ng-repeat= ...

Are there alternative methods for anchoring an element in Vuetify aside from using the v-toolbar component?

I have been working on positioning certain elements in the app and I have found a method that seems to work, using code like this: <v-toolbar fixed></v-toolbar> Another option is something along these lines: <v-toolbar app></v-toolb ...

What could be causing the issue with the theme not functioning properly in Material-UI?

I'm currently working on implementing a unique theme-switching feature in my web application, allowing users to toggle between light and dark modes. Utilizing the Material-UI framework combined with React, here's the code snippet: const theme = c ...

Detecting changes in URL hash using JavaScript - the ultimate guide

What is the most effective method for determining if a URL has changed in JavaScript? Some websites, such as GitHub, utilize AJAX to add page information after a # symbol in order to generate a distinct URL without having to refresh the page. How can one ...

Flow object with Angular using ng-flow: Existing flow object

Just a quick question that I can't seem to find an answer for on my own or through searching online. Currently, I have a button set up for clicking and uploading files. However, I also want to incorporate drag and drop functionality using the same fra ...

Issue: Unable to find solutions for all parameters in NoteService: (?)

After following a tutorial on Angular 2 from , I encountered the mentioned error when running my API. The browser indicates that there are unresolved parameters in the following service: import {Injectable} from '@angular/core'; import { ApiSe ...

The ng-message function appears to be malfunctioning

I am facing an issue with the angularjs ng-message not working in my code snippet. You can view the code on JSfiddle <div ng-app="app" ng-controller="myctrl"> <form name="myform" novalidate> error: {{myform.definition.$error ...

Ways to retrieve the current URL in Next.js without relying on window.location.href or React Router

Is there a way to fetch the current URL in Next.js without relying on window.location.href or React Router? const parse = require("url-parse"); parse("hostname", {}); console.log(parse.href); ...

Validating Two DateTime Pickers as a Group with Javascript in asp.net

How to Ensure Group Validation of Two DateTime Pickers Using JavaScript in ASP.NET ...

How to achieve multiplication in Javascript without utilizing the * operand

Challenge 1 Criteria: This problem involves working with two positive integers N and M. Outcome: Upon completion, the function should output the result of multiplying N and M. For instance, if you input 5 and 8 into the function, it should calculate and ...

Is there a way for me to record the variable's name instead of its linked data?

Currently, I am developing a node.js program that monitors the prices of different currencies. While I can successfully retrieve the prices, I would like the program to also display the names of the currencies along with their prices. In the code snippet b ...

Using .attr() to change the 'id' in jQuery will not be effective

Initially, the code has been streamlined to include only the necessary components. Here is the HTML file (single_lesson.html) in question: <tr class="my_lessons"> <td> <select name="my_von" id="my_von"></select> &l ...