Masking in SVG

Masking is really powerful in SVG in fact SVG has it’s own mask element specific to this purpose.

<mask id="myMask"></mask>

We can add this element into our <defs> tag and then any content we add inside of it will be used as a luminance mask. So black will become transparent and white remains opaque. Then we simply add the mask property referencing our mask element by id.

<rect mask="url(#myMask)"/>

SVG also supports clip paths, which work basically the same way as masks. We have our clip path element which contains the shape used as our clip path. Then we use the clip-path property to apply it to content within our SVG. The difference between clip paths and masks is that masks support semitransparent areas, such as gray colors and gradients, where clip paths just use the outline of the shape and make it either completely opaque or transparent.

<clipPath id="myClipPath"></clipPath>
<rect clip-path="url(#myClipPath)"/>

These techniques allow for some interesting designs, but also allow interesting animation techniques as well. For example, below is an animation I created that draws in text using a mask. In the video above I describe how it was made.

See the Pen Write In by CJ Gammon (@cjgammon) on CodePen.

Click here to download the demo.