代码之家  ›  专栏  ›  技术社区  ›  jbochi

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

  •  151
  • jbochi  · 技术社区  · 14 年前

    可以设置一个 background-image 对于SVG <path> 元素?

    例如,如果我设置元素 class="wall" CSS风格 .wall {fill: red;} 作品,但 .wall{background-image: url(wall.jpg)} 不是,也不是 .wall {background-color: red;} .

    2 回复  |  直到 7 年前
        1
  •  235
  •   Miguel    9 年前

    你可以通过把背景变成 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

        2
  •  12
  •   Miguel    9 年前

    “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);