Load Images from within objects with array

39 Views Asked by At

I have a class that I've created, called Sprite:

var Sprite = function Sprite()
{
that = this;
that.xPos = 0;
that.yPos = 0;
…
that.image = null;

this.render =function()
{
…
}
this.setImage(filename)
{
  that.image = new Image();
  that.image.src = filename;
}

}

And then I create an array of objects:

var names=[
{filename:"a1.png"},
{filename:"a2.png"},
{filename:"a3.png"},
{filename:"a4.png"}
];

var objs = [];
for(var l=0;l<names.length;l++)
{
  objs.push({});
  objs[l] = new Sprite();
  …
  setImage(names[l]);

}

Every object in my array point to the same image (with the same image file.)

Can anybody tell me what I'm doing wrong here?

Is there a better way I can do this?

Thanks.

1

There are 1 best solutions below

0
On BEST ANSWER

your setImage(names[l]); in the loop seems to be overwriting hence you get same image, try doing something like:

var Sprite = function Sprite() {
    that = this;
    that.xPos = 0;
    that.yPos = 0;
    that.image = null;

    this.setImage = function(filename) {
      that.image = new Image();
      that.image.src = filename;
    };
}

var names=[
    {'filename':"a1.png"},
    {'filename':"a2.png"},
    {'filename':"a3.png"},
    {'filename':"a4.png"}
];

var objs = [];
for(var l=0;l<names.length;l++) {
  var sp = new Sprite();
  //set image for the new sprite object
  sp.setImage(names[l].filename); 
  objs.push(sp);  //push sp object to objs array
}
console.log( objs );