Clipping and Masking

With clipping, you define the clipping shape with the <clipPath> element, and only those inside the clipping shape will be visible. It's an "all-or-nothing" approach: half-transparent effects are not possible.

Masking, on the other hand, allows soft edges by taking transparency and grey values of the mask into account (MDN).

You would declare <clipPath> and <mask> inside the <defs> element, and you must give the gradient an id attribute so you can reference it.

SVG elements

<clipPath>

  • clipPathUnitsdefines the coordinate system for the clipping path; specify userSpaceOnUse (use viewport/absolute coordinate) or objectBoundingBox (use the bounding box of the element that references this pattern, coordinate values will range from 0 to 1)
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
  <defs>
    <!-- only show the top part -->
    <clipPath id="clip-cut-off-bottom">
      <rect x="0" y="0" width="100" height="50" />
    </clipPath>
  </defs>
  <!-- see the clip-path attribute below -->
  <circle cx="50" cy="50" r="50" fill="red" clip-path="url(#clip-cut-off-bottom)" />
</svg>
| LIVE PREVIEW

<mask>

Everything under a white pixel will be visible; everything under a black pixel will be invisible ("white is ON, black is OFF").

  • xx coordinate offset of the masking area
  • yy coordinate offset of the masking area
  • widthwidth of the masking area; specify a number like 0.5 or 50% (will clip)
  • heightheight of the masking area; specify a number like 0.5 or 50% (will clip)
  • maskUnits defines the coordinate system for attributes x, y, width, height; specify userSpaceOnUse (use viewport/absolute coordinate) or objectBoundingBox (use the bounding box of the element that references this pattern, coordinate values will range from 0 to 1)
  • maskContentUnitsdefines the coordinate system for children elements of <mask>; specify userSpaceOnUse (use viewport/absolute coordinate) or objectBoundingBox (use the bounding box of the element that references this pattern, coordinate values will range from 0 to 1)
<svg xmlns="http://www.w3.org/2000/svg" width="300" height="100">
  <defs>
    <!-- gradient from white to black (to the right) -->
    <linearGradient id="gradient" x1="0" y1="0" x2="1" y2="0">
      <stop offset="0" stop-color="white" />
      <stop offset="1" stop-color="black" />
    </linearGradient>
    <!-- the mask -->
    <mask id="mask">
      <rect x="0" y="0" width="300" height="100" fill="url(#gradient)"  />
    </mask>
  </defs>
  <!-- see the mask attribute below -->
  <text x="20" y="75" font-size="60" fill="blue" mask="url(#mask)">
    Oh noes!
  </text>
</svg>
| LIVE PREVIEW
Oh noes!

References