javascript - 图片未定义onload函数,需要获取高度和宽度

标签 javascript image onload

我得到了这个代码:

_getWidthAndHeight = (ImageURL) => { 
    var img = new Image();
    img.onload = () => {
      alert(JSON.stringify(img));
      alert(this.height);
      alert(this.width);
    };
    img.src = ImageURL;
  }

它应该在谷歌浏览器中加载图像,并获取图像的高度和宽度。为什么对象返回空?

最佳答案

this 没有指向箭头函数中所需的内容

_getWidthAndHeight = (ImageURL) => { 
    var img = new Image();
    img.onload = function()  { // now "this" will be what you think it is
      console.log(this.height,this.width);
    };
    img.src = ImageURL;
  }
  
  _getWidthAndHeight("https://via.placeholder.com/500x400?text=500x400")

带箭头:

_getWidthAndHeight = (ImageURL) => { 
    var img = new Image();
    img.onload = (e) =>  { // now you can use e.target
      console.log(e.target.height,e.target.width);
    };
    img.src = ImageURL;
  }
  
  _getWidthAndHeight("https://via.placeholder.com/500x400?text=500x400")

关于javascript - 图片未定义onload函数,需要获取高度和宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59717929/

相关文章:

javascript - 将 jQuery 与来自 ES6 的类一起使用

javascript - Contenteditable 标签延续

javascript - 如何隐藏 ChartJs 上的第一个 Y 轴刻度线?

c++ - OpenCV 图像从 RGB 到 HSV 的转换

image - 在 React Native 中为图像添加填充?

Javascript - 是否使用 onload 事件

javascript - 如何使用 jQuery promises 链接三个异步调用?

java - jframe 中的多个 'imageviews'

javascript如何运行相同的功能onLoad和onChange

javascript - 为什么chrome会在这里抛出 "Uncaught Error: NOT_FOUND_ERR: DOM Exception 8"?