无法使用循环在画布中加载多个图像

时间:2013-01-26 09:08:18

标签: javascript html5 kineticjs

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

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

3 个答案:

答案 0 :(得分:0)

你需要一个闭包:

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

另见:

答案 1 :(得分:0)

请查看该链接。在coffeescript循环中加载图像

https://gist.github.com/4589644

答案 2 :(得分:0)

我通过从语句中删除return函数来解决问题。