0

I have this simple html showing an image.

<!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

The img element has different properties: width,height,offsetWidth,offsetHeight,naturalWidth,naturalHeight but none of them give the dimensions of the rendered image correctly.

How do I calculate the width, height and scale/zoom of the rendered image?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Janghou
  • 1,613
  • 1
  • 21
  • 30
  • No need for jsbin links when we have [Stack Snippets](https://meta.stackoverflow.com/q/358992/215552) (icon looks like `<>` on the editor toolbar). – Heretic Monkey Jan 20 '22 at 11:53
  • I would think this would be a matter of some simple math. `naturalWidth` and `naturalHeight` get the original width and height (200 & 300). So divide width by height those to get the aspect ratio. Then multiply that by the current height to get the current rendered width (because the aspect ratio < 1). I'll leave what to do when the aspect ratio is > 1 to you. – Heretic Monkey Jan 20 '22 at 12:03

1 Answers1

2

According to the specs

The replaced content is scaled to maintain its aspect ratio while fitting within the element’s content box.

So you have to take both the aspect ratio of the image (iAR) and the aspect ratio of the container element content box (ctAR) into account.

If the aspect ratio of the image > aspect ratio of the content box, the rendered image width takes all of the available space.

If the aspect ratio of the image < aspect ratio of the content box, the rendered image height takes all of the available space.

<!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>
Janghou
  • 1,613
  • 1
  • 21
  • 30