Skip to main content

Archive

Show more

Clipping and Masking in SVG

Clipping and Masking in SVG

Clipping and masking are techniques used in SVG (Scalable Vector Graphics) to control the visibility of elements by defining regions or patterns. Clipping is used to hide portions of elements outside of a specified region, while masking is used to selectively apply transparency to elements based on a defined pattern. Here's how to use clipping and masking in SVG:


1. Clipping

Clipping is achieved using the clipPath element to define a clipping path, and the clip-path attribute to apply the clipping path to an element.

Example:

<svg width="200" height="100">
  <defs>
    <clipPath id="clip">
      <rect x="0" y="0" width="100" height="50" />
    </clipPath>
  </defs>
  <circle cx="50" cy="50" r="40" fill="blue" clip-path="url(#clip)" />
</svg>

This example clips a blue circle to a rectangle defined by the clipping path.


2. Masking

Masking is achieved using the mask element to define a mask, and the mask attribute to apply the mask to an element.

Example:

<svg width="200" height="100">
  <defs>
    <mask id="mask" x="0" y="0" width="100" height="50">
      <rect x="0" y="0" width="100" height="50" fill="white" />
      <circle cx="50" cy="50" r="40" fill="black" />
    </mask>
  </defs>
  <rect x="0" y="0" width="100" height="100" fill="blue" mask="url(#mask)" />
</svg>

This example creates a mask consisting of a white rectangle and a black circle, and applies the mask to a blue rectangle, resulting in a portion of the rectangle being transparent based on the mask pattern.


3. Conclusion

Clipping and masking are powerful techniques for controlling the visibility and transparency of elements in SVG graphics. By defining clipping paths and masks, you can create complex visual effects and achieve precise control over the appearance of your SVG illustrations and designs.

Comments