user3274572
user3274572

Reputation: 11

Draw more images in canvas over each other

I am trying to plot more images where every new image cover the oldest. Iam using Google chrome, but the canvas code draws images in random order.

The function for drawing image is:

function paint_img(obrazek,x,y,sirka,vyska){

  var obrazekk = new Image();

  obrazekk.src = obrazek;

  obrazekk.onload = function(value) { 

  aaac.drawImage(obrazekk,x ,y ,sirka ,vyska);

  };

   //aaac.moveToTop();

   //aaac.stroke();

   //aaac.restore();

}

But when i am trying to draw more images their order is random. They are not drawen in order img1, img2, img3 and than img4 by (for example) this code:

for (i=1;i<=10;i++){

 paint_img("img"+i+".png",1,1,100,100)

}

I can not post example where the pictures are drawen in random order.

Upvotes: 1

Views: 130

Answers (1)

user1693593
user1693593

Reputation:

The random order is because the images finish loading in more or less random order.

You can solve this by a slightly different approach -

First create a loop that stores your image elements in an array:

var images = [],               /// image element array
    count = 10,                /// number of images to load
    loaded = count,            /// counter (decremented later)
    i = 1;

for (;i <= count;i++){
     var img = new Image();    /// create new image element
     img.onload = done;        /// set load handler
     img.src = "img"+ i +".png"; /// set source
     images.push(img);         /// push to array
}

This will guarantee the order of the images in our next step. As you can see the load handler is shared so we need to count number of images loaded:

function done() {
    loaded--;                  /// decrement loaded counter
    if (loaded === 0)          /// when done, draw images
        drawImages();
}

Now when the images has loaded we can draw them and they will be drawn in the order you would expect:

function drawImages() {
    for(var i = 0; i < images.length; i++) {
        aaac.drawImage(images[i], 1, 1, 100, 100);
    }

    /// continue your script from here...
}

The example here does not have an error handler which you of course should add at least in the final code.

Hope this helps!

Upvotes: 1

Related Questions