我需要弄清楚图像缩放了多少。
我正在使用 background-size: cover
为 body
设置背景图像。
基本上,无论屏幕尺寸如何,图像都会始终保持其宽高比并扩大(或缩小)直到它填满屏幕的宽度和高度。然后它会自行定位,使其垂直和水平居中,“多余”部分被裁剪掉。
假设我知道
- 原始背景图片大小
- 屏幕/视口(viewport)站点
我怎样才能知道图像实际缩放了多少?
最佳答案
如果我们假设您的图像尺寸为 WxH
并且屏幕尺寸为 AxB
那么它应该是 A/W
之间的最大值> 和 B/H
。
一些例子:
.box {
width:400px;
height:200px;
background:url(https://picsum.photos/300/300?image=0) center/cover;
}
/*
we will have 1.333 = 400/300 and 0.6667 = 200/300
*/
img {
transform:scale(1.3333);
transform-origin:top left;
}
<div class="box">
</div>
<img src="https://picsum.photos/300/300?image=0">
.box {
width:300px;
height:200px;
background:url(https://picsum.photos/500/500?image=0) center/cover;
}
/*
we will have 0.6 = 300/500 and 0.4 = 200/500
*/
img {
transform:scale(0.6);
transform-origin:top left;
}
<div class="box">
</div>
<img src="https://picsum.photos/500/500?image=0">
.box {
width:100px;
height:300px;
background:url(https://picsum.photos/400/300?image=0) center/cover;
display:inline-block;
}
/*
we will have 0.25 = 100/400 and 1 = 300/300
*/
img {
transform:scale(1);
transform-origin:top left;
}
<div class="box">
</div>
<img src="https://picsum.photos/400/300?image=0">
对于 contain
,我们取最小值:
.box {
width:400px;
height:200px;
background:url(https://picsum.photos/300/300?image=0) left/contain no-repeat;
}
/*
we will have 1.333 = 400/300 and 0.6667 = 200/300
*/
img {
transform:scale(0.6667);
transform-origin:top left;
}
<div class="box">
</div>
<img src="https://picsum.photos/300/300?image=0">
.box {
width:300px;
height:200px;
background:url(https://picsum.photos/500/500?image=0) left/contain no-repeat;
}
/*
we will have 0.6 = 300/500 and 0.4 = 200/500
*/
img {
transform:scale(0.4);
transform-origin:top left;
}
<div class="box">
</div>
<img src="https://picsum.photos/500/500?image=0">
.box {
width:100px;
height:300px;
background:url(https://picsum.photos/400/300?image=0) top/contain no-repeat;
display:inline-block;
}
/*
we will have 0.25 = 100/400 and 1 = 300/300
*/
img {
transform:scale(0.25);
transform-origin:top left;
}
<div class="box">
</div>
<img src="https://picsum.photos/400/300?image=0">
关于css - 使用背景大小:cover?时如何获取图像的比例百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55800201/