Html 用背景图像填充 SVG 路径元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3796025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:38:49  来源:igfitidea点击:

Fill SVG path element with a background-image

htmlcssimagesvgbackground-image

提问by jbochi

Is it possible to set a background-imagefor an SVG <path>element?

是否可以background-image为 SVG<path>元素设置 a ?

For instance, if I set the element class="wall", the CSS style .wall {fill: red;}works, but .wall{background-image: url(wall.jpg)}does not, neither .wall {background-color: red;}.

例如,如果我设置 element class="wall",CSS 样式.wall {fill: red;}有效,但.wall{background-image: url(wall.jpg)}无效,也无效.wall {background-color: red;}

回答by robertc

You can do it by making the background into a pattern:

您可以通过将背景变成图案来做到这一点:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image xlink:href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

根据您的图像调整宽度和高度,然后从路径中引用它,如下所示:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

工作示例