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

标签 javascript image javascript-objects

我正在寻找一种方法来查找传入图像的尺寸。 当我记录高度和宽度时,两者都返回 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;
}

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

关于javascript - 如何获取存储在 javascript 对象中的图像的宽度和高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45991200/

相关文章:

java - 如何在android中获取图像的(x,y)坐标?

image - 在xcode(cocoa应用程序)中插入图像

javascript - Zombie.js jQuery 加载错误 'j.getClientRects is not a function'

javascript - 使用它来选择具有相同名称的各种类中的不同类

javascript - 在 FOR 循环的特定元素上启动事件函数

javascript - 使用具有透明 PNG 的 Canvas 进行像素化调整大小

Javascript 对象和键

javascript - 更改 JavaScript 对象键和数据的位置

javascript - 为什么在 2 个检索值相加后无法执行 toFixed() 函数?

javascript - 有什么方法可以在 Flash 中显示 HTML 内容吗?