Javascript将图像绘制在彼此之上

时间:2013-06-03 01:32:13

标签: javascript html5 node.js socket.io html5-canvas

我正在使用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';
}   

1 个答案:

答案 0 :(得分:1)

Jonathan Lonowski是对的。对于每个onload触发器,cur指向同一个玩家,最后一个。 cur事件处理程序中只存在一个drawPlayers

使用此选项将cur的范围与循环中的范围分开:

function draw(sprite,cur){
  return function() {
    context.drawImage(sprite, cur.x, cur.y);
  };
}

然后从循环内部调用它

for(var i=0; i<players.length; i++){
  var cur = players[i];
  var playerSprite = new Image();
  playerSprite.onload = draw(playerSprite,cur);
  playerSprite.src = 'images/sprite.png';
  console.log("drawing player "+cur.un+" at ("+cur.x+","+cur.y+")");
}