How can I get the real height and width of an image inside a SVG element in HTML, when the width
attribute of it is expressed in percentage?
HTML code:
<svg id="svg-container" xmlns="http://www.w3.org/2000/svg">
<image id="content-image" href="page-003.jpg" width="90%">
</image>
</svg>
JS code:
let el;
el = document.getElementById("content-image");
console.log(el.clientWidth);
el = document.getElementById("svg-container");
console.log(el.clientWidth);
The two console.log
commands output 0 and 300, respectively. How can I get the real width of the image object?
2
Answers
From Documentation,
You have to use
width
property from getBoundingClientRect().Snippet
naturalHeight
&naturalWidth
property returns the originalheight
&width
of an image.NB: This property is read-only
The natural height and width of an image are not directly accessible through the SVG image element. Fortunately, by loading the image into a temporary
img
element and eventually accessing its native dimensions, you may still get the image’s original dimensions.HTML code:
JS code: