212

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

Simon East
  • 55,742
  • 17
  • 139
  • 133
jbochi
  • 28,816
  • 16
  • 73
  • 90
  • 2
    Showing how to set the background image for SVG text, optionally on a per-character basis: http://stackoverflow.com/a/10853878/405017 – Phrogz Jul 13 '12 at 20:51
  • 1
    for those looking for some more in deep info check this article [link](http://vanseodesign.com/web-design/svg-pattern-attributes/) – Paulo Bueno Aug 28 '16 at 13:40

1 Answers1

323

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

Razin
  • 221
  • 6
  • 15
robertc
  • 74,533
  • 18
  • 193
  • 177
  • 3
    very nice, does this work with base64 images too? instead of wall.jpg something like `data:image/png;base64,iVBORw0KGgoAA` like you would in normal CSS? – Christoph May 10 '12 at 13:55
  • 18
    @Christoph I don't know, try it and see. – robertc May 10 '12 at 14:09
  • 2
    @robertc I tried and it didn't work, but i had a duplicate style element. By eliminating it, it worked just fine;) – Christoph May 10 '12 at 14:20
  • 6
    @robertc: I have a question regarding your answer. The pattern starts at the global coordinates (0,0). Is it possible to let the pattern use the local coordinate system from the object attached to? I want to draw a rect at different places in my svg and what happens is, that the pattern is repeated in the hole background and the objects are used as masks. – Tobias Golbs Sep 17 '12 at 22:32
  • 1
    @TobiasKun I suggest you ask your own question. – robertc Sep 18 '12 at 02:50
  • This is a really helpful answer, especially if you're working with d3.js or other similar libs. Upvoted because damn, it saved me. – Protagonist Jul 02 '13 at 16:18
  • 1
    Unfortunately TCPDF doesn't support SVG Patterns, as I imagine other programs which don't yet have full SVG2 support don't either. – Joseph Coco Oct 23 '14 at 02:28
  • 9
    @robertc please update your answer to mention that `xlink:href` is deprecated since SVG 2 and to simply use `href` now. https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href – Blake Regalia Feb 19 '19 at 02:11