[英]How do I get the width and height of an image stored inside a javascript object?
I am looking of a way to find the dimensions of the passed in image. 我正在寻找一种方法来找到传递的图像的尺寸。 When I log the height and width it returns 0 for both.
当我记录高度和宽度时,两者都返回0。
function GamePiece(imageName){
this.image = new Image();
this.image.src = imageName;
this.width = this.image.width;
this.height = this.image.height;
}
You need to allow the browser time to load the image before you can get it's size. 您需要等待浏览器时间来加载图像,然后才能获取图像的大小。 You can use the
onload
callback to detect when the image is loaded. 您可以使用
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;
}
There will be a delay before the callback is run and the dimensions are set on your object. 在运行回调和在对象上设置尺寸之前会有一个延迟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.