I use FileReader + Canvas to resize and display the image. The preview image is not displayed in IE and Firefox (displayed only in chrome), although if you set an alert before writing base64 to src everything works correctly in all browsers. setTimeout and img.onload does not help, so I doubt that this is due to timing.

function preview(file, area) { //принимает с input type="file" данные и область в которую отображать данные if (file.type.match(/image.*/)) { var className = area.className; var reader = new FileReader(); reader.addEventListener("load", function(event) { var img = document.createElement("img"); img.src = event.target.result; // на этом этапе отображает корректно, но без ресайза //alert(1); // с этим алёртом все работает img.alt = file.name; img.className = "takeImg"; area.innerHTML = ""; if( className.indexOf('first') != -1 ) { img = cropImg(img); area.appendChild(img); } else if ......... и.т.д function cropImg(img) { var canvas = document.createElement("canvas"); var needW = 1000; var needH = 622; var w = (img.naturalWidth - needW)/2; var h = (img.naturalHeight - needH)/2; canvas.width = needW; canvas.height = needH; var ctx = canvas.getContext('2d'); for (var i = 5; i > 1.1; i -= 0.05) { if((img.naturalWidth >= (needW * i)) && (img.naturalHeight >= (needH * i))) { ctx.drawImage(img, 0,0,(needW * i),(needH * i),0,0,1000,622); break; } else { ctx.drawImage(img, w,h,1000,622,0,0,1000,622); } } var dataURL = canvas.toDataURL("image/png"); img.src = dataURL; return img; } 
  • You may find the answer to this question helpful : ru.stackoverflow.com/questions/565211/… - Duck Learns to Take Cover
  • Well, that is, I did not bother to debug, it should be otdebezhit normally, but my instinct tells me that this is due to asynchronous loading of images - Duck Learns to Take Cover sep
  • Finished the code to the snippet. - Qwertiy
  • @ Duck, from the heart brother, helped. The main thing setTimeout and img.onload, but the extreme degree of autism prevents even the right idea to implement) - Light
  • @Light, well, problems with understanding asynchrony arise at the beginning for everyone, do not worry) - Duck Learns to Take Cover

0