Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML5

How to Ensure Images are Loaded Before Rendering Them

4.60/5 (4 votes)
11 Mar 2012CPOL2 min read 17.9K  
Receiving INDEX_SIZE_ERR: DOM Exception 1 in HTML5 drawImage() function - Here is a small trick that helps to make sure that images are loaded before being rendered.

Okay, so I have been busy developing HTML5 games for a company, so I cannot share it here... but what I can share is a small trick that helps to make sure that my images are loaded before I go about rendering them:

The basic idea is this:

  • Make a list of all the images you want to upload
  • Create image objects for all the images listed above
  • Add "onLoad" event listener to each one of them such that the listener calls the same function, let's call it onImgLoad
  • Now comes our onImgLoad function which will be fired every time an image gets loaded enough that it can be rendered or at least that when trying to render the image, all the basic image data will be available so that no error is thrown.
    • Every time this function is called, we increment a variable, i.e., imgLoaded by 1
    • If the imgLoaded becomes equal to total number of images to be loaded, i.e., imgToLoad, we can now safely draw them.

Here is the code snippet where I'm loading 10 images, 1.png to 10.png from images folder.

C#
var imgLoaded = 0;
var imgToLoad = 10;
var onImgLoad = function()
{
   imgLoaded++;
   if(imgLoaded == imgToLoad)
   {
      drawImage()             //Call to our draw function
   }
}
 
for(var i = 0; i < 10; i++)
{
  images[i] = new Image();
  images[i].onload = onImgLoad;
  images[i].src = 'images/'+i+'.png';
}

Also a key point to note here is that...

C#
images[i].onload = onImgLoad;

...is assigned before providing the image source.

This is done as a hack for Internet Explorer (that's something I read in some post while I was hunting to solve this problem of mine).

Note: Updated article on the blog... not the code, but some more text on why and where? 

Note 2: As suggested by a couple of comments, I'm renaming the title (removing HTML5), however, my intention to include HTML5 in title was to ensure beginners searching for solution to error using HTML5 error code (INDEX_SIZE_ERR: DOM Exception 1) returned on failed drawImage() function, can find this blog easily. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)