unable to load multiple images into a canvas using a loop

advertisements

I am trying to load multiple images in a loop but no idea why it ain't working.

    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 will add layer to stage when all the images are loaded. Now why it is not showing images on the canvas whats the problem ?

EDIT:

Now i edited the code to work it with closures as @zeta suggested but still no success.Here's the edited code.

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


You need a closure:

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

See also:

  • How do JavaScript closures work?