javascripthtmlcssimage

Zoomed images don't have different sizes according to JavaScript


Is there any way to get the actual size of a zoomed image via javascript? After adding a css zoom affect to the image and then getting the size via JS it returns the original size.

var img = document.getElementById('img');
var box = document.getElementById('box')

box.innerHTML += "<br />height: " 
    + img.height +
    "px<br />width: "
    + img.width + "px";
#img{zoom:20%}
<div id="box">
  <img id="img" src="https://tse2.mm.bing.net/th/id/OIP.Lt_KplHna5Rxc5JdcOAXuQHaHa?rs=1&pid=ImgDetMain" />
</div>

https://codepen.io/tinkersncody/pen/dyxENwq


Solution

  • You can use the getBoundingClientRect() method:

    var img = document.getElementById('img');
    var box = document.getElementById('box')
    
    img.onload = () => {
      box.innerHTML += "<br />height: " 
        + img.getBoundingClientRect().height
        + "px<br />width: "
        + img.getBoundingClientRect().width
        + "px";
    }
    #img{zoom:20%}
    <div id="box">
      <img id="img" src="https://tse2.mm.bing.net/th/id/OIP.Lt_KplHna5Rxc5JdcOAXuQHaHa?rs=1&pid=ImgDetMain" />
    </div>

    img.onload = () => {...} is added to make sure image is loaded before getting the values.