<mask>
Allows you to define one or more parts to be hidden in an SVG tag with HTML.
The <mask>
tag is used in SVG to define a masked region where certain parts of an element are visible and others are not.
It allows you to create visual effects, such as transparencies, cutouts, or shadows.
Structure and syntax of the <mask>
tag
Structure
Here is a basic example:
HTML
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<defs>
<mask id="myMask">
<rect x="0" y="0" width="200" height="200" fill="white" />
<circle cx="100" cy="100" r="50" fill="black" />
</mask>
</defs>
<rect x="0" y="0" width="200" height="200" fill="orange" mask="url(#myMask)" />
</svg>
In this example:
- The
<mask>
tag defines a mask calledmyMask
; - We then create an orange rectangle with
<rect>
that is masked with this mask, making a circular area in the center visible; - The white areas of the mask are visible, and the black areas are transparent.
Here is the result:
Advanced example
Here is a more complex example using gradients and text:
HTML
<svg width="300" height="200" xmlns="http://www.w3.org/2000/svg">
<defs>
<mask id="textMask">
<rect x="0" y="0" width="300" height="200" fill="white" />
<text x="50" y="100" font-size="60" fill="black" font-family="Arial">MASK</text>
</mask>
</defs>
<rect x="0" y="0" width="300" height="200" fill="url(#gradient)" mask="url(#textMask)" />
<defs>
<linearGradient id="gradient" gradientTransform="rotate(90)">
<stop offset="0%" stop-color="red" />
<stop offset="100%" stop-color="blue" />
</linearGradient>
</defs>
</svg>
In this example:
- A text (
<text>
) mask is applied to a gradient rectangle; - Only the areas corresponding to the text are visible.
Try it yourself:
Attributes of the <mask>
tag
The <mask>
tag handles several attributes:
Attribute | Description |
---|---|
id | Unique identifier of the mask, used to reference it in other elements via mask="url(#id)" . |
maskUnits | Defines the coordinate system for the mask (userSpaceOnUse or objectBoundingBox ). |
maskContentUnits | Specifies the coordinate system for the content of the mask (userSpaceOnUse or objectBoundingBox ). |
x , y | Horizontal and vertical position of the mask. |
width , height | Dimensions of the mask. |
Browser compatibility
The <mask>
tag is compatible with most modern browsers:
Browser | Compatibility |
---|---|
Chrome | Yes |
Firefox | Yes |
Safari | Yes |
Edge | Yes |
Internet Explorer | Partial (with certain limitations) |