插件窝 干货文章 background-size: cover下,如何精确计算背景图片的缩放比例?

background-size: cover下,如何精确计算背景图片的缩放比例?

缩放 高比 宽度 偏移 802    来源:    2025-03-20

在使用 background-size: cover 时,背景图片会被缩放以完全覆盖容器的背景区域,同时保持图片的宽高比。为了精确计算背景图片的缩放比例,可以按照以下步骤进行:

1. 获取容器和图片的尺寸

  • 容器的宽度和高度:假设容器的宽度为 containerWidth,高度为 containerHeight
  • 图片的原始宽度和高度:假设图片的原始宽度为 imageWidth,高度为 imageHeight

2. 计算宽高比

  • 容器的宽高比containerAspectRatio = containerWidth / containerHeight
  • 图片的宽高比imageAspectRatio = imageWidth / imageHeight

3. 确定缩放比例

  • 如果 imageAspectRatio 大于 containerAspectRatio,则图片的宽度会被缩放以适应容器的宽度,高度会按比例缩放。
    • 缩放比例scale = containerWidth / imageWidth
  • 如果 imageAspectRatio 小于 containerAspectRatio,则图片的高度会被缩放以适应容器的高度,宽度会按比例缩放。
    • 缩放比例scale = containerHeight / imageHeight

4. 计算缩放后的图片尺寸

  • 缩放后的宽度scaledWidth = imageWidth * scale
  • 缩放后的高度scaledHeight = imageHeight * scale

5. 计算图片的偏移量(如果需要)

  • 如果图片的宽高比与容器的宽高比不同,图片可能会在某个方向上超出容器,此时需要计算图片的偏移量以居中显示。
    • 水平偏移量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 下背景图片的缩放比例和偏移量。