width/height
如果不设置,默认值与naturalWidth/naturalHeight相同。
设置方式:
Image(width, height)
var myImage = new Image(100, 200);
myImage.src = 'picture.jpg';
document.body.appendChild(myImage);
等价
<img width="100" height="200" src="picture.jpg">
等价(但CSS指定优先级更高)
// 方法1: 直接指定图片元素CSS属性
img {
width: 100px;
height: 200px;
}
// 方法2: 指定父元素CSS属性,再由100%等间接指定图片元素CSS属性
.parent {
width: 100px;
height: 200px;
}
img {
width: 100%;
height: 100%;
}
naturalWidth/naturalHeight
HTMLImageElement 接口的 naturalHeight 属性是一个只读值,它返回图像的固有(自然)密度校正高度(以 CSS 像素为单位)。 若不指定图像的宽高,则绘制时会使用naturalWidth/naturalHeight,如在CanvasRenderingContext2D.drawImage()方法中,若CanvasRenderingContext2D.drawImage(img, 0, 0),没有指定宽高时,会以naturalWidth/naturalHeight渲染宽高。
例子
(来源:developer.mozilla.org/en-US/docs/…
HTML
<div class="box">
<img src="/en-US/docs/Web/HTML/Element/img/clock-demo-400px.png" class="image">
</div>
<div class="output">
</div>
clock-demo-400px.png 图片为400x398像素
CSS
.box {
width: 200px;
height: 200px;
}
.image {
width: 100%;
}
.output {
padding-top: 2em;
}
通过css设置图片元素的宽度为200px,只设置宽度时,高度会等比缩放 398*(200/400)= 199px
JavaScript
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`;
});
自然宽高(naturalWidth/naturalHeight)只读,是400x398px;宽高(width/height)经过设置后,是200x199px。
Result
总结
width/height为图片元素的渲染宽高,naturalWidth/naturalHeight为图片本身的宽高,在不额外设置width/height时,两对值对应相等,图片元素以naturalWidth/naturalHeight为宽高进行渲染。