构造函数内部的img.width/height返回零



我有。。。

var img = new Image();
img.src = 'img.png';
function Class(img){
this.img = img;
console.log(this.img.width); //0
}
var instance = new Class(img);

上面代码中的控制台日志返回0,而与图像大小无关。

如果我把控制台日志放在更新功能中,并让它生成每一帧,它确实会返回正确的值

Element.prototype.update = function(){
console.log(this.img.width); //581
}

但我不希望它返回每帧的宽度。我只想在施工期间用一次。知道为什么img.width/height总是在构造函数内返回0吗?

因为图像资源的加载总是异步的。您需要等待其onload事件:

var img = new Image();
img.src = 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png';
function Class(img){
this.img = img;
img.onload = e => {
console.log(this.img.width);
};
}
var instance = new Class(img);

最新更新