xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

How to get the original size of an image using JavaScript All In One

How to get the original size of an image using JavaScript All In One

如何使用 JavaScript 获取一个图片像的原始大小

naturalWidth & naturalHeight

let output = document.querySelector(".output");
let image = document.querySelector("img");

window.addEventListener("load", (event) => {
  output.innerHTML += `Natural size: ${image.naturalWidth} x ` + `${image.naturalHeight} pixels<br>`;
  output.innerHTML += `Displayed size: ${image.width} x ` + `${image.height} pixels`;
});

https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/naturalWidth
https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/naturalHeight

Experimental ⚠️

https://developer.mozilla.org/en-US/docs/Web/API/PerformanceElementTiming/naturalWidth
https://developer.mozilla.org/en-US/docs/Web/API/PerformanceElementTiming/naturalHeight

WHATWG

The IDL attributes naturalWidth and naturalHeight must return the density-corrected natural width and height of the image, in CSS pixels, if the image has density-corrected natural width and height and is available, or else 0.

如果图像具有密度校正的自然宽度和高度并且可用,则 IDL 属性 naturalWidth 和 naturalHeight 必须返回图像的密度校正的自然宽度和高度(以 CSS 像素为单位),否则返回 0.

https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-naturalwidth
https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-naturalheight

image

https://caniuse.com/?search=naturalWidth %26 naturalHeight

demos

<img src="https://i.stack.imgur.com/deTzi.jpg?s=256&amp;g=1" alt="xgqfrms's user avatar" width="128" height="128" class="bar-sm bar-md d-block">
const img = document.querySelector(`img`);
img.naturalHeight;
// 256
img.naturalWidth;
// 256

image

aspect ratio / 纵横比

Rendered size:	128 × 128 px
Rendered aspect ratio:	1∶1
Intrinsic size:	256 × 256 px
Intrinsic aspect ratio:	1∶1
File size:	27.0 kB
Current source:	https://i.stack.imgur.com/deTzi.jpg?s=256&g=1
渲染尺寸:128 × 128 像素
渲染纵横比:1:1
内在尺寸:256 × 256 像素
固有长宽比:1:1
文件大小:27.0 kB
当前来源:https://i.stack.imgur.com/deTzi.jpg?s=256&g=1

https://stackoverflow.com/users/5934465/xgqfrms?tab=reputation

refs

https://stackoverflow.com/questions/77120785/display-images-side-by-side-with-equal-height



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @   xgqfrms  阅读(33)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2022-09-27 js performance.now vs console.time and console.timeEnd All In One
2022-09-27 道教辟谷养生 All In One
2022-09-27 MD5 加密算法 All In One
2022-09-27 HTML5 custom input form validate All In One
2021-09-27 js & async await & if else All In One
2021-09-27 CI/CD platform and version of Linux All In One
2021-09-27 Lerna In Action All In One
点击右上角即可分享
微信分享提示