skip to Main Content

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?

Link to JSFiddle

2

Answers


  1. From Documentation,

    The Element.clientWidth property is zero for inline elements and elements with no CSS;

    You have to use width property from getBoundingClientRect().

    const contentImage = document.getElementById("content-image");
    console.log(contentImage.getBoundingClientRect().width);
    
    const svgContainer = document.getElementById("svg-container");
    console.log(svgContainer.getBoundingClientRect().width);
    

    Snippet

    const contentImage = document.getElementById("content-image");
    console.log(contentImage.getBoundingClientRect().width);
    
    const svgContainer = document.getElementById("svg-container");
    console.log(svgContainer.getBoundingClientRect().width);
    <svg id="svg-container" xmlns="http://www.w3.org/2000/svg">
      <image id="content-image" href="https://images.unsplash.com/photo-1575936123452-b67c3203c357?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8Mnx8aW1hZ2V8ZW58MHx8MHx8fDA%3D&w=1000&q=80" width="90%"></image>
    </svg>
    Login or Signup to reply.
  2. naturalHeight & naturalWidth property returns the original height & 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:

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

    const svgContainer = document.getElementById('svg-container');
    const contentImage = document.getElementById('content-image');
    
    const img = new Image();
    img.src = contentImage.getAttribute('href');
    
    contentImage.addEventListener('load', () => {
      const height = img.naturalHeight;
      const width = img.naturalWidth;
    
      console.log(`Height: ${height}, Width: ${width}`);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search