Ani
Ani

Reputation: 1655

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

Upvotes: 8

Views: 3689

Answers (1)

KooiInc
KooiInc

Reputation: 122906

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

images[i].onload = onImgLoad;

Upvotes: 9

Related Questions