English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Using the SVG mask masking feature, you can apply the mask to SVG shapes. SVG masks are an advanced version of clipping paths, used to determine which parts of the SVG shape are visible and what transparency they have.
In SVG, you can reference a transparent mask layer and combine it with the current object to form the background. The transparent mask layer can be any other graphic object or <g> element. The mask element is used to define such a mask element. The mask attribute is used to reference a mask element.
Generate a blue rectangle mask
<svg height="450" width="450"> <defs> <mask id="mask1" x="0" y="0" width="100" height="100"> <rect x="0" y="0" width="100" height="100" style="stroke:none; fill: #ffffff"/> </mask> </defs> <rect x="1" y="1" width="200" height="200" style="stroke: none; fill: #0000ff; mask: url(#mask1)"/> </svg>Test and see‹/›
The effect after running is as follows:
The id attribute of the <mask> element defines the unique name of the mask.
The <rect> element of the <mask> defines the shape of the mask.
The style attribute of the <rect> element gives the mask ID element the mask CSS property.
Text Masking Effect
<svg width="200" height="80" viewBox="0 0 200 80" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <mask id="myMask" maskUnits="userSpaceOnUse" x="0" y="0" width="200" height="80"> <rect x="0" y="0" width="100" height="80" fill="white"/> </mask> <text id="Text" x="100" y="48" font-size="26" font-weight="bold" text-anchor="middle"> Black & White </text> </defs> <!-- Draw a black rectangle on the background --> <rect x="100" y="10" width="95" height="60"></rect> <!-- Draw the text string twice. First, white text without the mask. Second, apply the black text with the mask--> <use xlink:href="#Text" fill="white"/></use> <use xlink:href="#Text" fill="black" mask="url(#myMask)"/></use> </svg>Test and see ‹/›
The effect after running is as follows: