简体   繁体   中英

Scale image element in SVG to fit the SVG dimensions

I have an image element inside an SVG element. The href attribute of the image element and the width and height of the SVG element is set dynamically in JavaScript. I want the image element to fill up the parent SVG element.

<svg id="mySVG">
  <svg:g>
    <image id="bgImg" width="100%" height="100%"></img>
    ...
  </svg:g>
</svg>

Basically, I want the image element to be set as a background image of the SVG element.

Here are some examples. Most likely you need to make the size of the image match the viewBox of the svg.

Depending on your use case you can use preserveAspectRatio to control how the image behaves inside the SVG:

 svg { background-color: orange; }
 <p>Without setting the size:</p> <svg xmlns="http://www.w3.org/2000/svg"> <image href="https://via.placeholder.com/150"/> </svg> <p>The size of the image matches the viewBow of the SVG:</p> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 150 150"> <image href="https://via.placeholder.com/150"/> </svg> <p>And then control the size of the SVG with a width (or height) attribute:</p> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 150 150" width="100"> <image href="https://via.placeholder.com/150"/> </svg> <p>Same as above but with a viewBox that does not fit the size of the image and therefore the size of the image needs to be set explicitly:</p> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100"> <image href="https://via.placeholder.com/150" width="100" height="100"/> </svg> <p>Force the image to match the viewBox with preserveAspectRatio = none:</p> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 150"> <image href="https://via.placeholder.com/150" width="300" height="150" preserveAspectRatio="none"/> </svg>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM