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

时间:2010-09-25 23:48:03

标签: html css image svg background-image

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

例如,如果我设置元素class="wall",则CSS样式.wall {fill: red;}可以正常工作,但.wall{background-image: url(wall.jpg)}不会,.wall {background-color: red;}

2 个答案:

答案 0 :(得分:237)

您可以将背景变为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>

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

<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

答案 1 :(得分:13)

“robertc”的答案是svg - 这类似于d3.js路径代码所使用的。我设法通过应用以下内容为d3.js路径创建动态def。

我设法将其定义为以下

chart.append("defs")
     .append('pattern')
     .attr('id', 'locked2')
     .attr('patternUnits', 'userSpaceOnUse')
     .attr('width', 4)
     .attr('height', 4)
     .append("image")
     .attr("xlink:href", "locked.png")
     .attr('width', 4)
     .attr('height', 4);
相关问题