0

我正在尝试循环加载多个图像,但不知道为什么它不起作用。

    LoadCharactersImages2:function(Layer,roomObject)
    {
        var imgs = Array(5);
        var ImgBanners = Array(5);
        var sources = Array(5);
        var locationX = 100;            //x coordinate location of image
        var self = this;
            self.ImgloadCount = 0;



        sources[0] = "images/pacman/pacman_right.png";
        sources[1] = "images/pacman/pinkdown.png";
        sources[2] = "images/pacman/redleft.png";
        sources[3] = "images/pacman/yellowup.png";
        sources[4] = "images/pacman/blueright.png";

        for(var i = 0 ; i < 5;i++)
        {
            imgs[i] = new Image();
            imgs[i].src = sources[i];

            imgs[i].onload = function() {
                 ImgBanners[i] = new Kinetic.Image({
                  x: locationX,
                  y: 100,
                  image: imgs[i],
                });

                Layer.add(ImgBanners[i]);
                self.ImgloadCount++;
                self.AddtoStage(Layer,self);
                self.LoadUsersImages(self,roomObject,Layer);
            }

            locationX = locationX + 100;                
        }


    },

    AddtoStage:function(layer,self)
    {
        if(self.ImgloadCount == 5)
            self.stage.add(layer);
    },

AddtoStage加载所有图像后,将向舞台添加图层。现在为什么它没有在画布上显示图像是什么问题?

编辑:

现在我编辑了代码以使用@zeta建议的闭包但仍然没有成功。这是编辑后的代码。

            imgs[i].onload = (function(index){

         return function() {
             ImgBanners[index] = new Kinetic.Image({
              x: locationX,
              y: 100,
              image: imgs[index],
            });
                Layer.add(ImgBanners[index]);
                self.ImgloadCount++;
                self.AddtoStage(Layer,self);
                self.LoadUsersImages(self,roomObject,Layer);
                Layer.draw();
         }
        })(i);
4

3 回答 3

0

你需要一个闭包:

       imgs[i].onload = (function(index){
             return function() {
                 ImgBanners[index] = new Kinetic.Image({
                  x: locationX,
                  y: 100,
                  image: imgs[index],
                });
             })(i);

也可以看看:

于 2013-01-26T10:03:52.700 回答
0

我通过从语句中删除返回函数解决了这个问题。

于 2014-05-01T09:11:40.743 回答
0

请看一下那个链接。在咖啡脚本循环中加载图像

https://gist.github.com/4589644

于 2013-01-28T12:12:46.853 回答