javascript – NodeJS multiplayer game code problem


Hi, I'm having trouble creating a realtime game with node.js, below is the client part:

var position = {x:0, y:0};
var canvas = document.querySelector("canvas");
var context = canvas.getContext("2d");
var ws = io.connect("http://localhost:9090");

var keyboard = new Keys();


function draw(position) {
    context.fillRect(position.x, position.y, 50, 50);

function update() { 
    window.requestAnimationFrame(update, canvas);
    ws.emit("userMove", position);
    ws.on("serverUserPosition", draw);

And here's the server part:

var socket = require("").listen(9090);
socket.sockets.on("connection", run);

function run(user) {
    user.on("userMove", send);

function send(position) {
    socket.sockets.emit("serverUserPosition", position);

This code does the following, writes a rectangle on the screen every time a user enters and updates its position according to the user's movements. The problem is that the entire path of the rectangles on the screen is recorded and when using the context.clearRect(0, 0, canvas.width, canvas.height); he erases everything


When you use clearRect(0,0, width, height) you erase ALL your canvas. This is because the dimension of the rectangle you are erasing is equal to the dimension of your canvas. I didn't quite understand your question, but here we go:

  1. If you want to keep the entire history of rectangles on screen, you don't need to use clearRect. In that case you won't delete any of them.
  2. If you only want to delete a rectangle, you should use clearRect(position.x, position.y, 50, 50). This will erase the current rectangle. In case you want to erase the previous rectangle, just use an intermediate variable to store the previous x and y values.
Scroll to Top