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
This is also how it's possible to read websites offline; they're just being read off your hard drive. The idea of pre-loading images is to load them and put them in the cache before they're even needed. This means that when they are called for they'll appear almost immediately.
The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).
The image is considered completely loaded if any of the following are true: Neither the src nor the srcset attribute is specified. The srcset attribute is absent and the src attribute, while specified, is the empty string ( "" ). The image resource has been fully fetched and has been queued for rendering/compositing.
The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images.
You have to provide a reference to the load handler. Otherwise, the function executes immediately. Use:
images[i].onload = onImgLoad;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With