如何在画布上绘制多个数组实体

时间:2018-04-20 10:24:06

标签: javascript canvas

我想绘制出zombielist中的所有对象。但我无法让它发挥作用。

var FatZombieWikki = new Image();
FatZombieWikki.src = "FatZombieWikki.png";

var Zombie = function(x, y) {
  this.x = x;
  this.y = y;
  this.Draw = function(ctx) {
	ctx.drawImage(FatZombieWikki,200,ZombieY,50,50);
  }
  this.Update = function(){
	if(ZombieY < 900) {
	  ZombieY += 0.5;
	} 
  }
}

var z = new Zombie(100, 200,);
var zombieList = [];

for (var i = 0; i < 10; i++) {
  zombieList.push(new Zombie(40 * i, 100));
}

2 个答案:

答案 0 :(得分:3)

在创建对象之后,

在循环内调用绘制函数。

<强> 样本

var ctx = document.getElementById('c').getContext('2d');
var FatZombieWikki = new Image();
FatZombieWikki.src = "//i.stack.imgur.com/ubK40.jpg";

FatZombieWikki.onload = function(){
  var zombieList = [];

  for (var i = 0; i < 10; i++) {
    zombieList.push(new Zombie(40 * i, 30*i));
    zombieList[i].draw(ctx);
  }
}
var Zombie = function(x, y) {
  this.x = x;
  this.y = y;
  this.draw = function(ctx) {
    ctx.drawImage(FatZombieWikki,this.x,this.y,50,50);
  }
}
canvas{
 border:2px solid #000
}
<canvas id='c' width=500 height=400></canvas>

答案 1 :(得分:0)

zombieList.forEach(zombie => zombie.Draw(ctx))