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

Learn the process of zipping a folder in a Node.js application and initiating the download of the zip file afterwards

After encountering issues with the latest version of the npm package adm-zip 0.4.7, I reverted to an older version, adm-zip 0.4.4. However, despite working on Windows, this version does not function correctly on Mac and Linux operating systems. Additionall ...

What impact does nesting components have on performance and rendering capabilities?

Although this question may appear simple on the surface, it delves into a deeper understanding of the fundamentals of react. This scenario arose during a project discussion with some coworkers: Let's consider a straightforward situation (as illustrat ...

Unable to save the ID of an element into a jQuery variable

I am currently working on a project that involves an unordered list with anchor tags within it. I am trying to access the id of the li element that is being hovered over, but for some reason, the alert is returning undefined or nothing at all. Here is the ...

The fixed element alters its color when applied to a specific class within a div

I have a button with an icon and text that remains fixed on my webpage. The background colors of the sections change as you scroll through them, alternating between dark and light. I am looking for a solution where I can apply a class to multiple section ...

Creating auto serial numbers in the MERN stackWould you like to know how to

I need help coming up with a way to automatically generate serial numbers for my "ticketno" field. Every time a user creates a new application ticket, the ticket number should increment by one. Can someone guide me on how to achieve this? This i ...

Issue with manipulating element styles using jQuery in Angular2

My method of assigning IDs to elements dynamically using *ngFor looks like this: <div *ngFor="let section of questionsBySubCat" class="col-md-12"> <div class="subcat-container"> <h4 class="sub-cat">{{ section?.subcategory }}& ...

Can you show me a way to use jQuery to delete several href links using their IDs at once?

Currently facing a challenge with removing multiple href links that share the same ID. Here is a snippet of my code: $('.delblk').click(function(e) { e.preventDefault(); var id = $(this).attr('id').substr(7); ...

Tracking user sessions using cookies, not relying on JavaScript like Google does

Currently, I am working in an environment that utilizes PHP on the server side and Javascript on the client side. In order to monitor user sessions, I regularly send a JS PUT request to the server every 5 seconds. This allows me to gather data such as the ...

Error Message: ElectronJS - Attempted to access the 'join' property of an undefined variable

I am currently working on developing a tray-based application. However, I am encountering an error that reads: Uncaught TypeError: Cannot read property 'join' of undefined Can anyone guide me on how to resolve this issue? This is the content ...

"Implementing AngularJS bidirectional data binding to dynamically link user inputs with corresponding fields

Having trouble automatically outputting data with angularJS. One of the great features of angular is two-way data binding, but I can't seem to bind input with a JSON file. What I want to achieve is if the user's input matches a key, the correspon ...

What is the best method for storing a model in a database?

Hello, I am currently attempting to save a model to the database. I am simply inputting the value of a title in order to save it, as my id is set to auto increment. However, I have encountered an issue where my attempts have been unsuccessful. Can someone ...

I am unable to view the GridView features that have been set using jQuery in the JavaScript code on the webpage

I'm facing an issue with the properties of a GridView. On the aspx page, I have a container using a <div>. <div id="DivRecords"> Within this container, I am dynamically adding a GridView using jQuery. In the js file, I am creating the Gr ...

Issue with rendering D3 horizon chart is not displaying

I am attempting to create a horizon chart using D3.js and Horizon.js, inspired by this example from Jason Davies. I am working with fitness tracker data. However, the example by Mike Bostock uses a unique JSON structure and performs some complicated row-t ...

In Angular's production build on Webkit/Safari, the left-hand side of the operator '=' must be a reference

Recently, I completed a project using Angular. After successfully building it for production without any errors, everything seemed to work perfectly on Chrome. However, when attempting to run the app on Webkit/Safari, an error was displayed in the cons ...

How to mock nested functions within sinon

There are several questions similar to this one, but none of them quite match the scenario I'm dealing with. The situation involves a function that takes another function as a parameter: var myfunc = (func_outer) => { return func_outer().func ...

Add more JSON entries to the data submission in Express

Purpose: My goal is to ensure that the JSON data I submit is formatted correctly when it arrives in the JSON file, regardless of the number of entries I submit. Challenge: Currently, the data I submit does not append properly in the JSON file. It appear ...

Grabbing an AJAX Request

Currently, I am working on a Firefox extension that is designed to analyze the HTML content of web pages after they have been loaded in the browser. While I have successfully captured events like form submissions and link clicks, I am facing an issue wit ...

Can we pause and resume the progress bar using Javascript in conjunction with animationPlayState?

Looking for a way to control a progress bar script that runs for 180 seconds and then redirects the browser? Check out the code snippet below. I've added an onclick event to test pausing the progress bar. My goal is to pause, reset, and adjust the dur ...

call for axios within a line-up

Currently, I am using Axios to make request posts for a multi-step form. The process involves posting once in step one, then twice in step two, and so on. However, the issue arises when there is an internet bug causing the first request not to go through. ...

Troubleshooting CSS Hover Not Displaying Properly in Angular 14

In the footer class of my HTML, there is a code snippet with chevrons: <div class="link-list"> <div *ngFor="let link of insideLinksLeft | originalOrderKeyValue" class="link"> <a [href]="link.val ...