0

I want to draw out all of the objects that I have in my zombielist. but I can't get it to work.

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
  • Assuming that ctx.drawImage(FatZombieWikki,200,ZombieY,50,50); works, you now have to call the Draw() method of all the zombies inside the array. Commented Apr 20, 2018 at 10:28
  • @Shilly do you mean inside the for loop or inside the zombielist array? + the ctx.drawImage(FatZombieWikki,200,ZombieY,50,50); works Commented Apr 20, 2018 at 10:35

2 Answers 2

3

call your draw function inside loop, after creating object.

DEMO

var ctx = document.getElementById('c').getContext('2d');
var FatZombieWikki = new Image();
FatZombieWikki.src = "//i.sstatic.net/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>

Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

i get "ctx is not defined"
You said that ctx.drawImage(FatZombieWikki,200,ZombieY,50,50); works. You should use the same ctx here
Explain why or how this awnser would fix the problem instead of only a piece of code without any explaination.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.