设置图像src在Firefox上不起作用

时间:2014-12-12 10:18:24

标签: javascript html html5

我将获取所选图像的Url数据并将其放入已创建的图像对象中。我有Url数据,但此imgOrg.src = imgSrc;无法使用FireFox。任何想法为什么?

window.onload = function() {
  var reader, imgSrc, imgOrg;
  if (window.FileReader) {

    reader = new FileReader();
    reader.onloadend = function(e) {
      imgSrc = e.target.result;
      console.info(imgSrc);
    };
  }

  var avatarInput = document.querySelector('#imageFile');

  avatarInput.addEventListener('change', function(e) {
    console.info(imgOrg);
    imgOrg = {};
    var element = e.target;
    imgSrc = '';

    if (element.value !== '') {

      reader.readAsDataURL(e.target.files[0]);
      setTimeout(function() {
        imgOrg = new Image();
        imgOrg.src = imgSrc;

        console.log("imgOrg.src= " +
          imgOrg.src);
        console.log(imgSrc);
        console.log(imgOrg.width);
        console.log(imgOrg.height);

        var ratio = imgOrg.width / imgOrg.height;
        var fWidth, fHeight;
        if (ratio >= 1) {
          fWidth = 300;
          fHeight = (1 / ratio) * 300;
        }

      }, 1000);
    }
  }, false);
};
<input id="imageFile" type="file">

1 个答案:

答案 0 :(得分:0)

主要问题是:我试图在加载完成之前获取图像的宽度和高度。创建图像对象后,我将其余代码放入imgOrg.onload

window.onload = function() {
  var reader, imgSrc, imgOrg;
  if (window.FileReader) {

    reader = new FileReader();
    reader.onloadend = function(e) {
      imgSrc = e.target.result;
      console.info(imgSrc);
    };
  }

  var avatarInput = document.querySelector('#imageFile');

  avatarInput.addEventListener('change', function(e) {
    imgOrg = {};
    var element = e.target;
    imgSrc = '';

    if (element.value !== '') {

      reader.readAsDataURL(e.target.files[0]);
      setTimeout(function() {
        imgOrg = new Image();
        imgOrg.src = imgSrc;
        imgOrg.onload = function() {
          console.log("imgOrg.src= " +
            imgOrg.src);
          console.log(imgSrc);
          console.log(imgOrg.width);
          console.log(imgOrg.height);

          var ratio = imgOrg.width / imgOrg.height;
          var fWidth, fHeight;
          if (ratio >= 1) {
            fWidth = 300;
            fHeight = (1 / ratio) * 300;
          }
        }
      }, 1000);
    }
  }, false);
};
<input id="imageFile" type="file">