Image onload event not working in chrome

I use html5 to create drag and drop features. This works fine for me in firefox, but in chrome the onload event of the image only fires for the first time. If I drag several images only in the first works, and if I drag the second one, then it fails. I believe the problem is with the image loading.

this is how my code works, I deleted the unnecessary sections:

var img = document.createElement("img"); var reader = new FileReader(); var canvas = document.createElement("canvas"); var canvasData; var ctx = canvas.getContext("2d"); var myFiles; var i = 0; reader.onload = (function (aImg) { return function (e) { aImg.src = e.target.result; }; })(img); img.onload = function (){ //resizes image //draws it to the canvas //posts to server i++; if(i < myFiles.length){ processNext(i); } } function processNext(filei) { var file = myFiles[filei]; img.file = file; reader.readAsDataURL(file); } i = 0; myFiles = files; processNext(0); 

Does anyone know why this works in firefox but not in chrome?

+6
source share
2 answers

Explanation from the chrome tracker:

It's not a mistake. WebKit is just more rigorous. You must instantiate a new Image () object before replacing, for example:

 var photo = document.getElementById('image_id'); var img = new Image(); img.addEventListener('load', myFunction, false); img.src = 'http://newimgsource.jpg'; photo.src = img.src; 

source: http://code.google.com/p/chromium/issues/detail?id=7731#c12

+7
source

This is strange, none of the above worked for me. I defined the image variable as local and changed it to global, and it started working. Does this make sense? Can someone explain this?

This did not work for me:

 function loadImage() { var ImageToLoad = new Image(); imageToLoad.onload = function() { console.log("finish loading"); }; imageToLoad.src = "myimage.png"; } 

This worked:

  var ImageToLoad = new Image(); function loadImage() { imageToLoad.onload = function() { console.log("finish loading"); }; imageToLoad.src = "myimage.png"; } 
0
source

Source: https://habr.com/ru/post/886884/


All Articles