在一行中绘制多个图像

时间:2014-09-17 03:35:15

标签: javascript image

我如何简化这一点,所以它具有相同的效果?

context.drawImage(imgs2[0],enemy.x+135,enemy.y,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y2,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y3,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y4,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y5,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y6,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y7,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y8,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y9,tileWidth,tileHeight);

我在这个数组

中保存了“imgs2”
function images2(callback){
    for(var i = 0; i<enemy2.length; i++){
        var tile4 = new Image();
        imgs2.push(tile4);

        tile4.onload = function(){
            imagesdraw=true; 
            if (imagesdraw == true) {
                callback();
            }
        }
        tile4.src = enemy2[i];
    }
}

那么如何让drawImage变得更简单,所以它看起来并不那么简单,所以只有一行可以用于不同y的多个图像?

1 个答案:

答案 0 :(得分:2)

利用能够通过obj.["propertyToGet"]访问属性的优势,您可以简化:

ontext.drawImage(imgs2[0],enemy.x+135,enemy.y,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y2,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y3,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y4,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y5,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y6,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y7,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y8,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y9,tileWidth,tileHeight);

进入这个:

for(var i = 1; i <= 9; i++){
  var propertyName = "";
  if(i > 1){
    propertyName = "y" + i;
  }
  context.drawImage(imgs2[0],enemy.x+135,enemy[propertyName], tileWidth, tileHeight);
}

它看起来更干净。