CSS to Use an Image as a Mask
By Stephen Bucaro
People experienced in graphics design know that one way to make an image into a complex
shape is to use a mask. A mask is an image with one color that is transparent, allowing
an image behind it to show through, while a different color is used to block the parts of
the image behind it. There are many ways to accomplish masking, but none more simple than
using CSS (Cascading Style Sheets) to define an image to be used as a mask.
To use an image as a mask, first create a .png image and set the parts of the image that
you want to block to transparent. Set the parts of the image that you want to show through
to black. I know this sounds backwards, but that's the only way I've found it to work.
The use the CSS mask-image property to define the image as the mask.
I need to explain at this point that the CSS mask-image property works only in newer
versions of the Google Chrome browser, and only the -webkit-mask-image version works.
So at some point in the future things may change, especially since you're supposed to be
able to use the mask-type property to set which color is opaque and which is
transparent. But I'm not explaining the specification here, instead I'm giving you
examples that work.
The example above (which you can see if you're using the Google Chrome browser, is created
using the simple line of code shown below:
<img src="sunrise.jpg" style="-webkit-mask-image: url(mask.png);" />
Note that it is an html img tag that loads the image "sunrise.jpg" and then sets the
img elment's style to define "mask.png" as the mask. Very nice text created with an image.
Shown below is mask.png.
Shown below, we have set the background of the mask to black and the text part of the
mask to white.
This example is created using the simple line of code shown below:
<img src="riparion.jpg" style="-webkit-mask-image: url(phoenix.png);" />
Note that it is an html img tag that loads the image "riparion.jpg" and then sets the
img element's style to define "phoenix.png" as the mask. Very nice text on an image background.
Shown below is phoenix.png.
I've found that the only color text you can get is white because any color other
than transparent causes that area of the mask to be transparent, even white.
|