简体   繁体   中英

Fill SVG path element with a background-image

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

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;} .

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

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image 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

The answer by "robertc" is svg - and this is similar to what is used by d3.js path code. I managed to create dynamic def's for d3.js paths by applying the following.

I managed to get it working by defining it as the following

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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