admin管理员组

文章数量:1320652

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

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

Share Improve this question edited May 23, 2017 at 12:25 CommunityBot 11 silver badge asked Feb 10, 2012 at 12:11 AniAni 1,6553 gold badges23 silver badges37 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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

images[i].onload = onImgLoad;

本文标签: javascriptimageonload fires before image is completely loadedStack Overflow