如题,当图片尺寸小于容器时,直接按图片原尺寸显示就行了,可是当图片尺寸大于容器时,就要设法缩放图片以彻底装入容器,图片要尽量的匹配容器尺寸,并保持宽高比例(图片不能拉伸或挤压变形)。css
background-size: contain
background-size
是 CSS3 中的样式属性,属性值 contain
表示图像在保持原有比例的同时缩放到容器的可用空间的尺寸,以使其宽度和高度彻底适应容器尺寸,完整显示出来。html
.box {
width: 420px;
height: 300px;
background: url(https://cdn.pixabay.com/photo/2019/07/27/09/05/red-panda-4366264__340.jpg) no-repeat;
background-size: contain; /* 关键 */
border: 1px solid #ccc;
}
复制代码
<div class="box"></div>
复制代码
object-fit: contain
若是 DOM 结构由于某种限制,不能使用背景图片,而只能使用 <img>
插入图片,这种场景能够使用 object-fit: contain
CSS 声明,这里的属性值 contain
和 background-size
的 contain
效果相似。事实上 object-fit
属性可做用在可替换元素上,如 video、iframe 等,不限于图片。canvas
注意:IE 不支持这个属性ide
.box > img {
width: 100%;
object-fit: contain;
}
复制代码
<div class="box">
<img src="https://cdn.pixabay.com/photo/2019/07/27/09/05/red-panda-4366264__340.jpg">
</div>
复制代码
当没法使用上面两种自动化缩放的解决方案时,咱们得经过 JavaScript 来手动计算图片的实际渲染尺寸。(例如 canvas 绘图这种场景)ui
const temp = {
dWidth: 0
dHeight: 0
};
if (boxWidth >= imgWidth && boxHeight >= imgHeight) { // 照片小于等于容器尺寸
temp.dWidth = imgWidth;
temp.dHeight = imgHeight;
} else {
if (imgWidth >= imgHeight) { // 宽度优先
temp.dWidth = boxWidth;
temp.dHeight = imgHeight * boxWidth / imgWidth;
} else { // 高度优先
temp.dHeight = boxHeight;
temp.dWidth = imgWidth * boxHeight / imgHeight;
}
// 缩放后依然大于容器
if (temp.dWidth > boxWidth) {
temp.dHeight = temp.dHeight * boxWidth / temp.dWidth;
temp.dWidth = boxWidth;
} else if (temp.dHeight > boxHeight) {
temp.dWidth = temp.dWidth * boxHeight / temp.dHeight;
temp.dHeight = boxHeight;
}
}
console.log(temp);
复制代码
完整演示 Demo:codepen.io/wingmeng/pe…url