Recently I was looking to fill a text's background (an online postcard title) with an image and I was looking for a cross-browser solution that would work well.
The Idea is to apply a text (font) as a layer mask over the image. Achieving this kind of effect using only HTML (in a cross-browser way without using Flash/Silverlight…) was not possible, but now with SVG this can be done very easily.
This is the image I will use to fill the text's background with :
The first solution I tested was to declare the image and the Svg mask definition in the html and in the Css code marry the image to the mask using the css ‘mask’ property.
#myImg {
mask: url(#myMask);
}
This solution was perfect and straightforward but unfortunately it doesn’t work on webkit browsers like google chrome (the SVG code cannot be placed directly in the html, but need to be placed in an external svg file).
The 2nd solution I came up with to obtain the desired text effect, was to place an SVG object (containing the text mask) on the image. The SVG object can be placed directly on the image (using z-index), or inside a div containing the image in its background. in both cases the image should only be visible within the confine of the text's shape.
Here's the final result with the previous picture as the text's background :
The SVG text here have a 5px thick outline with a 100% transparency while the text fill have a 50% transparency value, the result is a nice hollow/glow like effect.
Html Code :
<div id="bkDiv">
<svg width="100%" height="100%">
<defs>
<mask id="theMask">
<rect width="100%" height="100%" fill="#fff" />
<text x="0" y="120" id="theText" fill="#000">Codicode</text>
</mask>
</defs>
<rect width="100%" height="100%" mask="url(#theMask)" fill="#000" />
</svg>
</div>
Css Code :
#bkDiv
{
background-image : url('my_image.jpg');
height:130px;
width:550px;
}
#theText
{
font-size:140px;
font-family:impact;
stroke:#000;
stroke-width:5px;
fill-opacity:0.5;
}
We also can render effects and animations in the text background instead of a steady picture when using Css3, check this
text background animation with svg and css3 tutorial.
Hope you like this and don't hesitate to comment and share, Thanks.
Chtiwi Malek on Google+About the author :
Malek Chtiwi is the man behind Codicode.com
34 years old full stack developer.
Loves technology; but also likes design, photography and composing music.