4

Is it possible to have background for text in svg or css? it means , every character have background? here is the example:

text with background mask

I have made this in photoshop and made a mask, i just wonder i it is possible in svg or css?

PFK
  • 116
  • 1
  • 1
  • 8
  • possible duplicate of [Fill SVG path element with a background-image](http://stackoverflow.com/questions/3796025/fill-svg-path-element-with-a-background-image) – robertc Jun 01 '12 at 07:58
  • 1
    This is element(like Circle or rectangle) not Text. I need for text – PFK Jun 01 '12 at 08:02
  • Yeah, realized that afterwards, trying to find the correct question this is duplicate of now. Text works exactly the same way though, [example](http://www.boogdesign.com/examples/svg/pattern-fill.svg). – robertc Jun 01 '12 at 08:04
  • 2
    [Here's the one specifically about text](http://stackoverflow.com/questions/3634663/masking-an-image-with-selectable-text-with-svg-possible/3636303#3636303). – robertc Jun 01 '12 at 08:07
  • tnx all. is there any possibility to have background for each character? – PFK Jun 01 '12 at 08:12

2 Answers2

18

Here is an example using a pattern. It uses <tspan> elements with patterned fill to show you how this may be done on a per-character basis, if desired:

Demo: http://jsfiddle.net/xWNR3/2/

The text "Hello World" with each letter of the first word filled with one pattern, and each letter of the second word filled with another pattern, except the "r" which is filled with the first pattern.

<svg xmlns="http://www.w3.org/2000/svg" xmlns:x="http://www.w3.org/1999/xlink">
  <style>
    svg  { background:#ddd }
    text {
      font-family:Verdana; font-size:160pt; font-weight:bold;
      stroke:#000;
    }
  </style>
  <defs>
    <pattern id="p1" patternUnits="userSpaceOnUse" width="32" height="32">
      <image x:href="alphaball.png" width="32" height="32" />
    </pattern>
    <pattern id="p2" patternUnits="userSpaceOnUse" width="10" height="10">
      <image x:href="grid.gif" width="10" height="10" />
    </pattern>
  </defs>
  <text x="20" y="170" fill="url(#p1)">
    Hello
    <tspan x="20" y="350"
           fill="url(#p2)">Wo<tspan fill="url(#p1)">r</tspan>ld</tspan>
  </text>
</svg>
Phrogz
  • 296,393
  • 112
  • 651
  • 745
2

You can use a mask or a clipPath to do this too, in addition to the way with patterns as in the answers robertc suggested.

Here's an example from the svg testsuite using clipPath.

Erik Dahlström
  • 59,452
  • 12
  • 120
  • 139