简体   繁体   English

缩放 SVG 中的图像元素以适应 SVG 尺寸

[英]Scale image element in SVG to fit the SVG dimensions

I have an image element inside an SVG element.我在 SVG 元素中有一个图像元素。 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. image元素的href属性和SVG元素的宽高是在JavaScript动态设置的,我想让image元素填满父SVG元素。

<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.基本上,我希望将图像元素设置为 SVG 元素的背景图像。

Here are some examples.这里有些例子。 Most likely you need to make the size of the image match the viewBox of the svg.您很可能需要使图像的大小与 svg 的 viewBox 匹配。

Depending on your use case you can use preserveAspectRatio to control how the image behaves inside the SVG:根据您的用例,您可以使用preserveAspectRatio来控制图像在 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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