3
Hello, I’m having trouble creating a real-time 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();
update();
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("socket.io").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
I do not understand. At first, what its function
draw
should do is draw the screen entire every frame of animation (or at least every frame that something has changed). That is, first she "erases everything" and then she draws everything that has to be drawn. Or did I misinterpret your question?– mgibsonbr