js 获取图片的原始尺寸的几种方法

Javascript 2020-03-15 阅读 310 评论 0

获取图片的真实尺寸,方便于我们进行一些图片样式的处理,如等比例缩放图片,能做到图片的自然显示。

使用图片的属性 naturalWidth

img 的 html 标签有很多有用的属性。如 width 和 height,是图片当前显示的宽和高,naturalWidth 和 naturalHeight,是图片的实际的宽度高度,记住一定要在加载完成事件 onload 中获取。参考HTMLImageElement.naturalWidth,不是所有的浏览器都支持这个 natural 属性。

<script>
function getSize(event) {
    console.log(event.width, event.height);
    console.log(event.naturalWidth, event.naturalHeight);
}
</script>
<img src="https://www.baidu.com/img/bd_logo1.png" style="width: 50px;" onload="getSize(this)">

亲手试一试 »

使用 Image 对象

参考 Image() 文档,构造 Image 对象时,如果不指定宽和高,width 和 height 就是图片的真实大小。

var image = new Image(100, 100);
image.src = "https://www.baidu.com/img/bd_logo1.png";
image.onload = function () {
    var str = "图片的显示尺寸:" + this.width + " x " + this.height;
    str += "
"
; str += "图片的原始尺寸:" + this.naturalWidth + " x " + this.naturalHeight; document.getElementById("result").innerHTML = str; }

亲手试一试 »

使用 jquery 代码

使用 jquery 的 load 事件回调。

$("").prop("src", "https://www.baidu.com/img/bd_logo1.png").on("load", function (){
    var str = this.width + " x " + this.height;
    $("#result").html(str);
})

亲手试一试 »

最后更新 2020-03-15