Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for multiple images loaded

I'm using the canvas feature of html5. I've got some images to draw on the canvas and I need to check that they have all loaded before I can use them.

I have declared them inside an array, I need a way of checking if they have all loaded at the same time but I am not sure how to do this.

Here is my code:

var color = new Array();
color[0] = new Image();
color[0].src = "green.png";
color[1] = new Image();
color[1].src = "blue.png";

Currently to check if the images have loaded, I would have to do it one by one like so:

color[0].onload = function(){
//code here
}
color[1].onload = function(){
//code here
}

If I had a lot more images, Which I will later in in development, This would be a really inefficient way of checking them all.

How would I check them all at the same time?

like image 352
Stanni Avatar asked Jun 13 '10 12:06

Stanni


3 Answers

Can't you simply use a loop and assign the same function to all onloads?

var myImages = ["green.png", "blue.png"];

(function() {
  var imageCount = myImages.length;
  var loadedCount = 0, errorCount = 0;

  var checkAllLoaded = function() {
    if (loadedCount + errorCount == imageCount ) {
       // do what you need to do.
    }
  };

  var onload = function() {
    loadedCount++;
    checkAllLoaded();
  }, onerror = function() {
    errorCount++;
    checkAllLoaded();
  };   

  for (var i = 0; i < imageCount; i++) {
    var img = new Image();
    img.onload = onload; 
    img.onerror = onerror;
    img.src = myImages[i];
  }
})();
like image 81
RoToRa Avatar answered Sep 30 '22 07:09

RoToRa


If you want to call a function when all the images are loaded, You can try following, it worked for me

var imageCount = images.length;
var imagesLoaded = 0;

for(var i=0; i<imageCount; i++){
    images[i].onload = function(){
        imagesLoaded++;
        if(imagesLoaded == imageCount){
            allLoaded();
        }
    }
}

function allLoaded(){
    drawImages();
}
like image 34
Harsimrat Singh Avatar answered Sep 30 '22 08:09

Harsimrat Singh


Use the window.onload which fires when all images/frames and external resources are loaded:

window.onload = function(){
  // your code here........
};

So, you can safely put your image-related code in window.onload because by the time all images have already loaded.

More information here.

like image 35
Sarfraz Avatar answered Sep 30 '22 07:09

Sarfraz