Using SVG masks for cut out text effects
Friday, March 13, 2009 4:35:20 PM
Have you ever wanted to use those cut out text effects, such as those that can be seen on postcards and posters, where the text is filed with an image, and the background outside the text is a solid colour or a different image or pattern? This is difficult to do in HTML without using an image or something like Flash, but with SVG it is trivially easy, especially when you know how.
first of all you need a image, that the text will be applied over. For this example I used a Creative Commons licenced image of the New York Skyline found on Flickr, by Ingo Meironke. This is included in a SVG file using the regular image element. Most of the magic happens in the defs section, where we define a mask out of the text. First we make a mask element as a child of defs, and set up the size of the mask, and its ID. Next, we add a child text element, containing the text we want to use as the mask — in this case, New York City — and position the text within the mask. Finally in the CSS file, the mask property is applied to the image, with the URL of the mask element (which is the path of the SVG file with the ID of the mask element as the fragment identifier). It then applies the text as a mask over the image, blocking out the image outside the bounderies of the text glyphs. In the example below, I also used a test outline. Including the stroke property on the mask text actually makes the stroke semi transparent, due to the mask, so I had to create a duplicate text element, with a stroke applied, and add it before the image element, so it shows behind the masked text (alternatively a z-index could be used to position it behind the masked text). For some reason, that I haven't worked out yet, Firefox shows this outline as offset to the right, making it look more like a solid shadow than a outline. Safari doesn't seem to support masking yet, so just displays the text with no fill. The final result can be seen below if you have a compatible browser:
The image above is reduced in size to fit in this blog post, and embedding with the img element doesn’t work well in all browsers, so to see it at the intended size go directly to my SVG mask example file.
One of the good points about using SVG for this technique (one all browsers support it), is that the text applied is plain text in a text element. It is in theory accessible to screen readers and search engine spiders, and is fully localisable, translatable and the text can be dynamically changed, all without generating new images.

Jeff Schillerjeffschiller # Friday, March 13, 2009 5:56:50 PM
If you put the CSS inline into the SVG document (wrapped in a svg:style element), then the effect shows up across the SVG browsers. For demo purposes, that's what I'd suggest.
Fredrik Anderssonfred # Friday, March 13, 2009 6:14:44 PM
David Storeydstorey # Saturday, March 14, 2009 3:08:29 AM
Fredrik Anderssonfred # Saturday, March 14, 2009 9:16:08 AM