【问题标题】:FileReader onload only works the second time around in Firefox?FileReader onload 仅在 Firefox 中第二次起作用?
【发布时间】:2015-08-07 03:06:07
【问题描述】:

我正在使用 HTML5 进行浏览器内图像处理,并且在 Firefox 中使用 File API FileReader 类的 onload 事件处理程序(在 chrome 上正常工作)有一个奇怪的问题:文件仅在第二次正确处理它在表单中被选中。

知道如何让 Firefox 首次处理此事件吗?

Ps:我使用的是 Linux,也许这有关系?

JSFiddle:https://jsfiddle.net/ow126vah/

代码:

var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');

fileInput.addEventListener('change', function(e) {

  var file = fileInput.files[0];
  var imageType = /image.*/;

  if (file.type.match(imageType)) {

    var reader = new FileReader();

    reader.onload = function(e) {

      var ctx = fileDisplayArea.getContext("2d");

      // create a new image from user selected file
      var img = new Image();
      img.src = reader.result;

      // set canvas size to image size
      fileDisplayArea.width = img.width;
      fileDisplayArea.height = img.height;

      // scale and draw image with offset
      ctx.drawImage(img, 0, 0);
    }
    reader.readAsDataURL(file);
  } else {
    alert("File not supported!");
  }
})
<div>Select an image file:
  <input type="file" id="fileInput">
</div>
<canvas id="fileDisplayArea"></canvas>

【问题讨论】:

    标签: javascript firefox dom


    【解决方案1】:

    问题不在于 FileReader。负载处理程序每​​次都会执行。问题似乎与访问图像的时间有关。等到加载完毕:

    // create a new image from user selected file
    var img = new Image();
    img.onload = function() {
      // set canvas size to image size
      fileDisplayArea.width = img.width;
      fileDisplayArea.height = img.height;
    
      // scale and draw image with offset
      ctx.drawImage(img, 0, 0);
    };
    img.src = reader.result;
    

    我认为它第二次可以工作,因为图像以一种或另一种方式缓存。

    【讨论】:

    • 花了一点时间来理解你的意思,但这很有效。谢谢! jsfiddle.net/ow126vah/3
    • 哇,当你说它并且它有效时,它真的很明显。你知道为什么 FF 在这种情况下工作方式不同吗?在任何浏览器中使用 img.onload 确实是有意义的,但在任何其他浏览器中都不需要它,而不是 FF。他们会自动等到图像加载完毕吗?
    【解决方案2】:

    对于 Firefox,我们需要等待:

    //ecouteur sur le chargement du reader
    reader.onload = function(e) {
    
        var img = new Image();
        img.src = reader.result;
    
        //Attendre fin du chargement de l'image...
        setTimeout(function(){ my_action_to_modify_image;}, 500);//Increase this value if doesn't work
    }
    

    【讨论】:

    • 虽然这可行,但它只是一个半好的解决方案。按照 Felix 的建议等待 img.onload 更好,因为您基本上是在猜测加载图像需要多长时间。
    猜你喜欢
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 2012-07-09
    相关资源
    最近更新 更多