JavaScript 程序:获取图像的尺寸

示例:获取图像的尺寸

// program to get the dimensions of an image

const img = new Image();

// get the image
img.src = '//cdn.programiz.com/sites/tutorial2program/files/cover-artwork.png';

// get height and width
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() 函数用于访问图像的高度和宽度。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战