【问题标题】:How to calculate the rendered dimensions of an image styled with object-fit: contain如何计算使用 object-fit 样式的图像的渲染尺寸:包含
【发布时间】:2022-01-20 22:44:14
【问题描述】:

我有一个显示图像的简单 html。

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width" />
  <title>Image Object Fit</title>
  <style>
    body {
      margin: 0;
      width: 100vw;
      height: 100vh;
    }
    
    img {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
  </style>
</head>

<body>
  <img src="https://placekitten.com/200/300" alt="" />
</body>

</html>

https://jsbin.com/hapoqog/edit?html,output

img 元素具有不同的属性:width,height,offsetWidth,offsetHeight,naturalWidth,naturalHeight,但它们都没有正确给出渲染图像的尺寸。

如何计算渲染图像的宽度、高度和缩放/缩放?

【问题讨论】:

  • 当我们有 Stack Snippets 时不需要 jsbin 链接(图标在编辑器工具栏上看起来像 &lt;&gt;)。
  • 我认为这将是一些简单的数学问题。 naturalWidthnaturalHeight 获取原始宽度和高度(200 和 300)。因此,将宽度除以高度以获得纵横比。然后将其乘以当前高度以获得当前渲染宽度(因为纵横比 1 时,我会留给你做什么。

标签: html css image browser object-fit


【解决方案1】:

根据specs

被替换的内容被缩放以保持其纵横比,同时 适合元素的内容框。

所以你必须同时考虑图像的纵横比(iAR)和容器元素内容框(ctAR)的纵横比。 p>

如果图像的纵横比>内容框的纵横比,则渲染的图像宽度会占用所有可用空间。

如果图像的纵横比纵横比,则渲染的图像高度会占用所有可用空间。

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width" />
  <title>Image Object Fit</title>
  <style>
    body {
      margin: 0;
      width: 100vw;
      height: 100vh;
    }
    
    img {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
  </style>
</head>

<body>
  <img src="https://placekitten.com/200/300" alt="" />
</body>
<script>
let img = document.querySelector("img");
img.onload = (e) => {
  let { width, height, naturalWidth, naturalHeight } = img;
  let iAR = naturalWidth / naturalHeight;
  let ctAR = width / height;
  let [w, h] =  iAR >= ctAR ? [width, width / iAR] : [height * iAR, height];
  let s = w / naturalWidth;
  console.log(w, h, s); // rendered width,height and scale
};
</script>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 2019-02-02
    • 2021-07-31
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    相关资源
    最近更新 更多