Click here to Skip to main content
13,042,421 members (138,344 online)
Rate this:
Please Sign up or sign in to vote.
I'm making a game using javascript + canvas. I use the code below to ensure
var imgLoaded = 0;
var imgToLoad = multiImgs;
var onImgLoad = function()
   if(imgLoaded == imgToLoad)
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 10-Feb-12 1:15am
Martin Arapovic 10-Feb-12 14:06pm

Try to google preload images or somthing. I think that I saw a solution for this using jquery...
SAKryukov 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.
SAKryukov 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"? :-)
SAKryukov 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).
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

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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;

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170713.1 | Last Updated 13 Feb 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100