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=".Lt_KplHna5Rxc5JdcOAXuQHaHa?rs=1&pid=ImgDetMain" />
</div>
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/th/id/OIP.Lt_KplHna5Rxc5JdcOAXuQHaHa?rs=1&pid=ImgDetMain" />
</div>
https://codepen.io/tinkersncody/pen/dyxENwq
Share Improve this question edited Nov 19, 2024 at 0:56 Timur 2,2971 gold badge6 silver badges14 bronze badges asked Nov 18, 2024 at 21:41 MikeMike 6177 silver badges27 bronze badges 3 |1 Answer
Reset to default 2You 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/th/id/OIP.Lt_KplHna5Rxc5JdcOAXuQHaHa?rs=1&pid=ImgDetMain" />
</div>
img.onload = () => {...}
is added to make sure image is loaded before getting the values.
codepen
, maybe it is very reliable and will last a thousand years. But we have no control on that), probably ephemere, site. Plus, SO already have the equivalent with snippets. – chrslg Commented Nov 19, 2024 at 0:24+
for strings, don't use<br>
, and don't setinnerHTML
unless you really need to set HTML code. Put a span in that div, and set its.textContent
using template string syntax. E.g.const span = box.querySelector(`span`); span.textContent =`height: ${...}, width: ${...}`;
) – Mike 'Pomax' Kamermans Commented Nov 19, 2024 at 1:25