使用数组从对象中加载图像

Load Images from within objects with array

我创建了一个 class,名为 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;
}

}

然后我创建一个对象数组:

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]);

}

数组中的每个对象都指向同一个图像(具有相同的图像文件。)

谁能告诉我我做错了什么?

有没有更好的方法可以做到这一点?

谢谢。

你的setImage(名字[l]);在循环中似乎被覆盖因此你得到相同的图像,尝试做类似的事情:

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 );