views:

61

answers:

3

Hi,

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?

+2  A: 

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.

Sarfraz
This doesn't seem to solve it. I've implemented the window.onload event handler around the function caller that starts off the whole script but it still runs too early.
Stanni
A: 

A hackish way to do it is add the JS command in another file and place it in the footer. This way it loads last.

However, using jQuery(document).ready also works better than the native window.onload.

You are using Chrome aren't you?

Aaron Harun
Yes, I'm using Chrome.
Stanni
Yah, the window.onload running early is a chrome bug. You can use browser sniffing with a setTimeout to delay it for chrome specifically.
Aaron Harun
Right I see, Thanks.
Stanni
+1  A: 

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];
  }
})();
RoToRa