Creative Coding with SVGs
zuubaDigital

Masks

codepen practice page

the mask element

Like clipPaths, masks are used to reveal/hide parts of another image. Unlike clipPaths, which are either “on” or “off”, a mask applies an alpha to the masked element. Everything under a white pixel is visible, while everything under a black pixel is invisible. The darker the shade of grey, the more transparent the masked element is.

patternpatternpattern with mask applied

Masks are defined by the <mask> element, and applied to a group or shape element using the mask attribute. The element has an id attribute used to identify and apply the mask.

<mask id="my-mask"...
...
<rect mask="url(#my-mask)" ...

mask gradient

Masks require a white-to-black gradient of some sort. The gradient should be defined in defs and given an id so that it can be used by the mask.

1 2 3 4 5 6 <defs> <radialGradient id="gradient"> <stop offset="0%" stopColor="white" /> <stop offset="100%" stopColor="black" /> </radialGradient> </defs>

Once you have your gradient you can create your mask. Masks are also defined inside of the defs section, like all other reusable elements.

1 2 3 4 5 6 7 8 9 10 11 12 <defs> // radial gradient code <mask id="gradient_mask"> <rect x="0" y="0" width="500" height="500" fill="url(#gradient)"> </rect> </mask> </defs>

Finally, you can apply the mask to a shape element or group by using it's id.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <defs> <radialGradient id="gradient"> // radial gradient code </radialGradient> <mask id="gradient_mask"> // mask code </mask> </defs> <rect mask="url(#gradient_mask)" x="0" y="0" width="500" height="500" fill="url(#simple_tile)">