js实现图片保持纵横比(等比例)缩放

240 阅读1分钟

前言

图片过大想要以图片本身的分辨率缩放至某个div容器中。类似于uniapp中image组件的 mode="aspectFit" 属性。

实现

html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    .rectangle {
      width: 800px;
      height: 500px;
      background: #000000;
      background-size: contain;
      position: relative;
    }
    .www{
      background: #00ffff;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  </style>
</head>
<body>
<div class="rectangle">
  <div class="www"></div>
</div>
<script >
  const www = document.querySelector('.www');
  const Wid = 800; // 容器盒子 宽
  const Hei = 500; // 容器盒子 高
  const w = 7680; // 图片实际分辨率-宽
  const h = 1080; // 图片实际分辨率-高  let width = 0;  // 图片等比例缩放后的宽  let height = 0; // 图片等比例缩放后的高  if (w/h > Wid/Hei) {
    width = Wid;
    height = Wid * (h/w);
  } else if (w/h < Wid/Hei) {
    width = Hei * (w/h);
    height = Hei;
  } else {
    width = Wid;
    height = Hei;
  }
  www.style.width = width + 'px';
  www.style.height = height + 'px';
</script>
</body>
</html>

如图是7860x1080等比例缩放后的效果。

对比效果:

原图

scaleToFill:不保持纵横比缩放图片,使图片完全适应

aspectFit:保持纵横比缩放图片,使图片的长边能完全显示出来