繁体   English   中英

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

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

我在 SVG 元素中有一个图像元素。 image元素的href属性和SVG元素的宽高是在JavaScript动态设置的,我想让image元素填满父SVG元素。

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

基本上,我希望将图像元素设置为 SVG 元素的背景图像。

这里有些例子。 您很可能需要使图像的大小与 svg 的 viewBox 匹配。

根据您的用例,您可以使用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