If I load multiple images in a for loop, do I need only one img.onload function?

Therefore, I upload several images to several canvases mainly (one image per canvas / ctx - its slide show). I want every image to load before trying to draw an image on canvas.

Here is the code ...

  • In Example 1, I use 3 onload events (one for each image)
  • In example 2, I use one onload event, but this is the last image that is called in the for loop

Question: Can I use Example 2 and be sure that if the last image is uploaded, then the previous images must be uploaded?

Also ---- I already tried to do this, but can everything be done in a for loop? I could not get it to work. See example 3

Example 1 3 onload events

var img=[0,'slide1','slide2','slide3']; for (var i=1;i<=3;i++) { img[i] = new Image(); img[i].src = '/images/slide' + i + '.png' } img[1].onload = function() { // checks to make sure img1 is loaded ctx[1].drawImage(img[1], 0, 0); }; img[2].onload = function() { // checks to make sure img2 is loaded ctx[2].drawImage(img[2], 0, 0); }; img[3].onload = function() { // checks to make sure img3 is loaded ctx[3].drawImage(img[3], 0, 0); }; 

Example 2 only the last onload event

 var img=[0,'slide1','slide2','slide3']; for (var i=1;i<=3;i++) { img[i] = new Image(); img[i].src = '/images/slide' + i + '.png' } img[3].onload = function() { // checks to make sure the last image is loaded ctx[1].drawImage(img[1], 0, 0); ctx[2].drawImage(img[2], 0, 0); ctx[3].drawImage(img[3], 0, 0); }; 

Example 3 one load in a for loop to execute all onload events

 var img=[0,'slide1','slide2','slide3']; for (var i=1;i<=3;i++) { img[i] = new Image(); img[i].src = '/images/slide' + i + '.png' img[i].onload = function() { // checks to make sure all images are loaded ctx[i].drawImage(img[i], 0, 0); }; } 

I suppose I cannot do Example 3 because the image probably will not be loaded by the time the loop cycle starts a second time and overwrites the onload event for the next image, thereby erasing the onload event for the previous image. Right?

+4
source share
1 answer

You will have trouble viewing the last for-loop due to closing. For something like this to work, you will want to break the loop by encapsulating your functionality in its own function. This article explains this well.

Ideally, your last for loop would look something like this:

 var images = [0,'slide1.png', 'slide2.png', 'slide3.png']; // Assign onload handler to each image in array for ( var i = 0; i <= images.length; i++ ){ var img = new Image(); img.onload = (function(value){ return function(){ ctx[value].drawImage(images[value], 0, 0); } })(i); // IMPORTANT - Assign src last for IE img.src = 'images/'+images[i]; } 

Also, keep in mind that you need to assign the img.src attribute AFTER the onload handler has been defined for some IE variants. (This little tidbit cost me an hour of troubleshooting last week.)

+7
source

All Articles