image.onload fires before image is completely loaded
Asked Answered
L

1

8

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

Lucey answered 10/2, 2012 at 12:11 Comment(0)
K
9

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

images[i].onload = onImgLoad;
Kutch answered 10/2, 2012 at 12:17 Comment(2)
Thanks. Gross oversight on my part!Lucey
I was wondering why my method got executed right away. Thank you for this solution! As for someone new to JavaScript this isn't that obvious, though I understand it because of your comment :)Purdah

© 2022 - 2024 — McMap. All rights reserved.