如何获取存储在javascript对象中的图像的宽度和高度



我正在寻找一种方法来查找传入图像的维度。当我记录高度和宽度时,两者都返回0。

function GamePiece(imageName){
this.image = new Image();
this.image.src = imageName;
this.width = this.image.width;
this.height = this.image.height;
}

在获取图像大小之前,需要让浏览器有时间加载图像。您可以使用onload回调来检测图像何时加载。

function GamePiece(imageName){
var gamePiece = this;
this.image = new Image();
this.image.onload = function() {
gamePiece.width = this.width;
gamePiece.height = this.height;
}
this.image.src = imageName;
}

在运行回调和在对象上设置维度之前会有一段延迟。

最新更新