Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

image.onload fires before image is completely loaded

I'm making a game using javascript + canvas. I use the code below to ensure

var imgLoaded = 0;
var imgToLoad = multiImgs;
var onImgLoad = function()
{
   imgLoaded++;
   if(imgLoaded == imgToLoad)
   {
      ctx.drawImage()
   }
}

for(var i = 0; i < multiImgs; i++)
{
  images[i] = new Image();
  images[i].onload = onImgLoad();
  images[i].src = 'images/'+i+'.png';
}

This code at times works fine, esp. when the images are cached. However, when loading for the first time, at times, it gives INDEX_SIZE_ERR: DOM Exception 1 which I found is due to height & width of image not being available as suggested by Quickredfox in this answer... but then here drawImage is called only when all the images are loaded? The error primarily occurs in mobile devices

like image 382
Ani Avatar asked Feb 10 '12 12:02

Ani


People also ask

Why does my website load images first?

This is also how it's possible to read websites offline; they're just being read off your hard drive. The idea of pre-loading images is to load them and put them in the cache before they're even needed. This means that when they are called for they'll appear almost immediately.

How does image onload work?

The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

How do you know if an image is fully loaded?

The image is considered completely loaded if any of the following are true: Neither the src nor the srcset attribute is specified. The srcset attribute is absent and the src attribute, while specified, is the empty string ( "" ). The image resource has been fully fetched and has been queued for rendering/compositing.

Which event occurs when page image has been loaded?

The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images.


1 Answers

You have to provide a reference to the load handler. Otherwise, the function executes immediately. Use:

images[i].onload = onImgLoad;
like image 62
KooiInc Avatar answered Sep 28 '22 17:09

KooiInc