我正在使用 node.js + socket.io 来尝试制作一个乘数 HTML5 画布游戏。不幸的是,每次我去画所有的球员时,所有的图像最终都会重叠在一起。
socket.on('drawPlayers', function(players){
context.clearRect ( 0 , 0 , gameWidth , gameHeight ); //clear canvas
for(var i=0; i<players.length; i++){
var cur = players[i];
var playerSprite = new Image();
playerSprite.onload = function() {
return context.drawImage(playerSprite, cur.x, cur.y);
};
playerSprite.src = 'images/sprite.png';
console.log("drawing player "+cur.un+" at ("+cur.x+","+cur.y+")");
}
});
console.log() 将正确记录不同的 x 和 y 值,但所有图像最终都相互重叠。
function player(id,username){
this.id = id;
this.un = username;
this.y = Math.floor(Math.random() * 501);
this.x = Math.floor(Math.random() * 801);
this.src = 'images/mobile_md_logo.png';
}
我