Problems with onload event when loading images

0

Good, I have a loop that runs through an array in which there may or may not be loaded images, the issue is that when you crash these images on a canvas and do it in the way you specify in MSDN, I can only load the last image the same number of times I have images in the array. This happens because the image is painted with the onload event that is called at the end of the loading of the page, so the loop has already finished and therefore I only have the information of the last iteration.

       for (var i=0; i<array.length; i++){
         var data=array[i].campoImagen;
         var DOMURL = window.URL || window.webkitURL || window;
         var img = new Image();
         var svg = new Blob([data], {type: 'image/svg+xml'});
         var url = DOMURL.createObjectURL(svg);
         img.onload = function() { 
           ctx.drawImage(img, Window.posx,Window.posy);
           DOMURL.revokeObjectURL(url);
         }
         img.src=url;
       }

Also, another problem is that in this way the images are always drawn on top of the texts because they are the last ones to be loaded on the canvas.

Any alternative to load each image in its corresponding iteration?

    
asked by Quarkbite 21.08.2017 в 09:52
source

1 answer

0

You are redefining the variable img in each iteration of the loop.

You could do it declaring each variable as an array

var img = [],
    svg = [],
    url = [],
    DOMURL = window.URL || window.webkitURL || window;    
for (var i=0; i<array.length; i++){
     var data=array[i].campoImagen;

     var img[i] = new Image();
     var svg[i] = new Blob([data], {type: 'image/svg+xml'});
     var url[i] = DOMURL.createObjectURL(svg[i]);
     img[i].onload = function() { 
       ctx.drawImage(img, Window.posx,Window.posy);
       DOMURL.revokeObjectURL(url[i]);
     }
     img[i].src=url[i];
   }

Although it would be smarter to define a function where each variable has scope only in the function.

var DOMURL = window.URL || window.webkitURL || window;
var procesaImg = function(data) {
     var img = new Image();
     var svg = new Blob([data], {type: 'image/svg+xml'});
     var url = DOMURL.createObjectURL(svg);
     img.onload = function() { 
       ctx.drawImage(img, Window.posx,Window.posy);
       DOMURL.revokeObjectURL(url);
     }
     img.src=url;
};

for (var i=0; i<array.length; i++){
     var data=array[i].campoImagen;
     procesaImg(data);
}
    
answered by 22.08.2017 / 14:02
source