如题,当图片尺寸小于容器时,直接按图片原尺寸显示就好了,但是当图片尺寸大于容器时,就要设法缩放图片以完全装入容器,图片要尽可能的匹配容器尺寸,并保持宽高比例(图片不能拉伸或挤压变形)。
-
background-size: contain
background-size 是 CSS3 中的样式属性,属性值 contain 表示图像在保持原有比例的同时缩放到容器的可用空间的尺寸,以使其宽度和高度完全适应容器尺寸,完整显示出来。
.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 等,不限于图片。
注意:IE 不支持这个属性
.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>
-
通过 js 计算
当无法使用上面两种自动化缩放的解决方案时,我们得通过 JavaScript 来手动计算图片的实际渲染尺寸。(例如 canvas 绘图这种场景)
思路:
- 图片载入成功后获取其宽高;
- 判断宽高是否小于或等于容器宽高,如是,则直接按原图尺寸显示即可;
- 如图片宽高大于容器宽高(宽度大于容器宽高,或高度大于容器宽高,或两者皆有之),取图片宽、高最大的一个进行等比缩放;
- 缩放完毕后再进行一次与容器尺寸的判断(不排斥有些变态的图);
- 如尺寸依然大于容器尺寸,则以大于容器的宽度或高度为基准,再进行一次等比缩放;
- 最终将缩放完成的图显示出来。
关键代码:
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…