Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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]. önload = 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... but then here drawImage is called only when all the images are loaded?

The error primarily occurs in mobile devices

Posted
Comments
Martin Arapovic 10-Feb-12 14:06pm    
Hi,

Try to google preload images or somthing. I think that I saw a solution for this using jquery...
Sergey Alexandrovich Kryukov 12-Feb-12 14:45pm    
Yes, probably. I would also suggest that this behavior is correct and good to use. The image is kind of loaded but not completely visualized. Using this even could be good enough, because the image is "loaded enough" to make the size of the image known, so it won't shift the page layout at later time. If so (I'm not sure, that's why this is only a comment), using this event could be good for many practical purposes. As to this case... I need to know what ctx.DrawImage does, will ask OP.
--SA
Sergey Alexandrovich Kryukov 12-Feb-12 14:40pm    
Maybe, this is just a behavior of mysterious event "önload" (I have no idea what is it:), in contract to "onload"? :-)
--SA
Sergey Alexandrovich Kryukov 12-Feb-12 14:46pm    
What ctx.DrawImage does? Why do you need an image fully loaded prior the the call (I understand, it sounds naive, but nevertheless... please see my comment above).
--SA
Aniruddha Loya 13-Feb-12 2:11am    
Hey guys, thanks for the inputs...
I had made a simple mistake here which was causing the error - images[i].onload = onImgLoad; -- the function was getting executed instead of being set as callback for onload event. As a result, the draw was happening even when the image was not partially loaded enough to provide the required data for the Draw function.
@SAKryukov - ctx.DrawImage is basically a call to draw the loaded image on the canvas (I placed a dummy here removing the actual code)

1 solution

I found the answer

Actually it was a coding error on my part -

instead of
images[i].onload = onImgLoad();


it should be
images[i].onload = onImgLoad;
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900