在使用 background-size: cover
时,背景图片会被缩放以完全覆盖容器的背景区域,同时保持图片的宽高比。为了精确计算背景图片的缩放比例,可以按照以下步骤进行:
containerWidth
,高度为 containerHeight
。imageWidth
,高度为 imageHeight
。containerAspectRatio = containerWidth / containerHeight
imageAspectRatio = imageWidth / imageHeight
imageAspectRatio
大于 containerAspectRatio
,则图片的宽度会被缩放以适应容器的宽度,高度会按比例缩放。
scale = containerWidth / imageWidth
imageAspectRatio
小于 containerAspectRatio
,则图片的高度会被缩放以适应容器的高度,宽度会按比例缩放。
scale = containerHeight / imageHeight
scaledWidth = imageWidth * scale
scaledHeight = imageHeight * scale
offsetX = (scaledWidth - containerWidth) / 2
offsetY = (scaledHeight - containerHeight) / 2
假设容器的宽度为 800px
,高度为 600px
,图片的原始宽度为 1920px
,高度为 1080px
。
const containerWidth = 800;
const containerHeight = 600;
const imageWidth = 1920;
const imageHeight = 1080;
const containerAspectRatio = containerWidth / containerHeight;
const imageAspectRatio = imageWidth / imageHeight;
let scale;
if (imageAspectRatio > containerAspectRatio) {
scale = containerWidth / imageWidth;
} else {
scale = containerHeight / imageHeight;
}
const scaledWidth = imageWidth * scale;
const scaledHeight = imageHeight * scale;
const offsetX = (scaledWidth - containerWidth) / 2;
const offsetY = (scaledHeight - containerHeight) / 2;
console.log(`缩放比例: ${scale}`);
console.log(`缩放后的宽度: ${scaledWidth}`);
console.log(`缩放后的高度: ${scaledHeight}`);
console.log(`水平偏移量: ${offsetX}`);
console.log(`垂直偏移量: ${offsetY}`);
缩放比例: 0.4166666666666667
缩放后的宽度: 800
缩放后的高度: 450
水平偏移量: 0
垂直偏移量: -75
在这个例子中,图片的宽度被缩放到了 800px
,高度被缩放到了 450px
,并且图片在垂直方向上需要向上偏移 75px
以居中显示。
通过这种方式,你可以精确计算出 background-size: cover
下背景图片的缩放比例和偏移量。