跳到主要内容

JavaScript 程序:获取图像的尺寸

示例:获取图像的尺寸

// 程序用于获取图像的尺寸

const img = new Image();

// 获取图像
img.src = "cover-artwork.png";

// 获取高度和宽度
img.onload = function () {
console.log("width " + this.width);
console.log("height " + this.height);
};

输出

width 1040
height 922

在上述程序中,使用了 new Image() 构造函数来创建一个图像对象。

Image() 构造函数创建了一个新的图像元素实例。

然后使用 img.src 来通过图像 URL 源添加图像。

img.onload() 函数用于访问图像的高度和宽度。