我得到了这个代码:
_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/