我想加载远程图像以获取其高度和宽度,但得到不同的结果。
下面的代码给了我正确的图像高度和宽度
img.onload= function() {
console.log('image;', this.width, this.height);
ctx.drawImage(img, 0, 0, width, height);
};
img.src = url;
但我得到了undefined
如果我使用箭头函数,则高度和宽度的值如下:
img.onload=() => {
console.log('image;', this.width, this.height);
ctx.drawImage(img, 0, 0, width, height);
};
img.src = url;
谁能告诉我为什么我不能在箭头函数中得到它?如何获取箭头函数的大小?
箭头函数没有自己的this
绑定,因此它使用它所封闭的那个。
要获得它,请定义一个event
范围。并使用event.currentTarget.width
.
img.onload = event => {
console.log('image;', event.currentTarget.width, event.currentTarget.height);
ctx.drawImage(img, 0, 0, width, height);
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)