Skip to content
Tutorials Center
My learning

Topics

Lesson 82 of 122 ยท Graphics

SVG Clipping, Masks, Filters and Animation

Cut shapes with clipPath, fade them with masks, blur, tint and distort them with SVG filter primitives, and animate SVG with SMIL elements or CSS animations.

Shapes, paths and gradients let you draw almost anything. This lesson is about what you can do to a drawing after it exists: cut it into a new outline, fade parts of it away, blur it, recolor it, warp it, and set it in motion. All of these effects are built into SVG itself, need no images and stay sharp at every size.

You will meet four tools: <clipPath> for hard-edged cutouts, <mask> for soft, partial transparency, <filter> for pixel effects such as shadows and noise, and the animation elements <animate>, <animateTransform> and <animateMotion>, compared with plain CSS animation. This builds on SVG Basics and SVG Paths, Text and Gradients, so make sure <defs>, id and url(#id) feel familiar.

Clipping with clipPath

A clipping path is a stencil. Anything inside its outline is drawn; anything outside is cut away completely. You define it once inside <defs> and apply it with the clip-path attribute:

HTML
<defs>
  <clipPath id="porthole">
    <circle cx="160" cy="100" r="90" />
  </clipPath>
</defs>
<image href="/samples/sunset.svg" width="320" height="200" clip-path="url(#porthole)" />

Only the geometry of the shapes inside <clipPath> matters. Their fill, stroke and opacity are ignored, and every pixel is either fully shown or fully hidden. A clipping path can contain several shapes (their areas add up) and even <text>, which gives you text-shaped windows.

By default the clip shape uses the same coordinate system as the element it clips (clipPathUnits="userSpaceOnUse"). Set clipPathUnits="objectBoundingBox" and the coordinates become fractions of the clipped element's box, from 0 to 1, so one clip path fits shapes of any size.

Clip paths: circle, text and star

The same idea works for ordinary HTML: CSS clip-path: url(#fx-round) on an <img> or <div> uses an SVG clip path defined anywhere in the page. For simple shapes, the CSS functions circle(), polygon() and inset() are often easier; CSS Clip Paths and Masks covers them.

Soft edges with mask

A mask is like a clipping path that understands shades of gray. Instead of "in or out", every point of the masked element gets an amount of visibility:

  • Where the mask content is white, the element is fully visible.
  • Where it is black (or empty), the element is hidden.
  • Grays in between give partial transparency.

This default is called a luminance mask: brightness decides visibility. Add mask-type="alpha" to the <mask> element and only the mask's opacity counts, which is handy when your mask shape is drawn in a brand color.

Masks shine when you combine them with gradients. A white-to-black gradient inside a mask makes an element fade out smoothly, something a clip path can't do.

Masks: a fade and a hole

In the second drawing, the black circle in the mask punches a hole, and the gray text makes the green show through at about half strength, so the checkerboard is visible behind it. Change fill="#808080" to white or black and watch the text disappear into the green or become a second hole.

Clip or mask? Use <clipPath> when you only need an outline: it's simpler, and browsers can do hit-testing and rendering faster. Reach for <mask> when you need soft edges, fades or partial see-through areas.

Filters: pixel effects in SVG

A <filter> is a small image-processing pipeline. It contains one or more filter primitives, elements whose names start with fe ("filter effect"). Each primitive takes an input image, changes it and produces an output. You apply the whole filter with the filter attribute:

HTML
<filter id="soft">
  <feGaussianBlur stdDeviation="4" />
</filter>
<circle cx="60" cy="60" r="40" fill="teal" filter="url(#soft)" />

Primitives connect through two attributes:

  • in names the input. SourceGraphic is the element itself, SourceAlpha is its shape as a black silhouette, and any other name refers to an earlier primitive's result. Without in, a primitive uses the output of the one before it.
  • result names a primitive's output so later primitives can use it.

These are the primitives you'll reach for most often:

Primitive What it does Key attributes
feGaussianBlur Blurs the input stdDeviation (blur radius; two values blur x and y differently)
feDropShadow Adds a blurred, offset shadow dx, dy, stdDeviation, flood-color, flood-opacity
feColorMatrix Changes colors type = saturate, hueRotate, luminanceToAlpha or matrix; values
feOffset Shifts the input dx, dy
feFlood Fills the region with one color flood-color, flood-opacity
feComposite Combines two inputs in, in2, operator (over, in, out, atop, xor, arithmetic)
feMerge Stacks several inputs child <feMergeNode in="..."> elements
feTurbulence Generates noise from nothing type, baseFrequency, numOctaves, seed
feDisplacementMap Pushes pixels around using another image in2, scale, xChannelSelector, yChannelSelector

The filter region

A filter only paints inside its filter region. By default that region is the element's bounding box plus 10% on every side (x="-10%" y="-10%" width="120%" height="120%"). A big blur or a long shadow can spill past that edge and get chopped off with a hard line. If you see a cut-off shadow, enlarge the region:

HTML
<filter id="big-shadow" x="-30%" y="-30%" width="160%" height="160%">
  <feDropShadow dx="8" dy="10" stdDeviation="8" flood-opacity="0.4" />
</filter>
Blur, drop shadow and color matrix

The glow filter shows the pipeline idea: the blur's output gets the name haze, and feMerge stacks it under the untouched SourceGraphic. Try a stdDeviation of 12 on the glow, or values="0.4" on the saturate filter for a faded, vintage look.

type="matrix" is the most powerful form of feColorMatrix. Its values are 20 numbers in four rows, one row each for the new red, green, blue and alpha. Each row says how much of the old R, G, B and A to mix in, plus a constant. For example, this matrix keeps the shape but paints every pixel solid indigo with its original opacity:

HTML
<feColorMatrix type="matrix" values="
  0 0 0 0 0.31
  0 0 0 0 0.27
  0 0 0 0 0.90
  0 0 0 1 0" />

More filter primitives

The remaining primitives are less common, but each solves a problem nothing else does.

Primitive What it does Key attributes
feBlend Mixes two inputs like image-editor layer modes in, in2, mode (multiply, screen, darken, lighten, ...)
feComponentTransfer Remaps each color channel with a curve; children feFuncR, feFuncG, feFuncB, feFuncA type = identity, table, discrete, linear or gamma, plus tableValues, slope, intercept, exponent
feConvolveMatrix Applies a convolution kernel: sharpen, emboss, edge detection order, kernelMatrix, divisor, bias, targetX, targetY, edgeMode, preserveAlpha
feMorphology Grows (dilate) or shrinks (erode) shapes operator, radius
feImage Brings an image or another element into the pipeline href, preserveAspectRatio
feTile Repeats the input as a tile across the filter region in (a small tile, made with a subregion x, y, width, height)
feDiffuseLighting, feSpecularLighting Light the alpha channel as if it were a height map surfaceScale, diffuseConstant, specularConstant, specularExponent, lighting-color
feDistantLight, fePointLight, feSpotLight The light source, placed inside a lighting primitive azimuth and elevation; x, y, z; a spot light adds pointsAtX, pointsAtY, pointsAtZ, limitingConeAngle

A few details are worth knowing:

  • feComponentTransfer treats every channel as a number from 0 to 1. With type="discrete" and tableValues="0 0.5 1" a channel can only end up as 0, 0.5 or 1, which gives a posterized look. type="gamma" computes amplitude * value^exponent + offset.
  • feConvolveMatrix multiplies each pixel and its neighbors by the numbers in kernelMatrix (order="3" means a 3 by 3 grid, so nine numbers) and adds them up. The sum is divided by divisor (the sum of the kernel by default), and bias is added afterwards. edgeMode decides what counts as a neighbor beyond the image edge: duplicate, wrap or none. Set preserveAlpha="true" to leave transparency alone.
  • Lighting filters build a lit surface from the shape's alpha channel. Blur the alpha first so the "surface" has soft slopes, then light it. feSpecularLighting adds shiny highlights; feDiffuseLighting gives matte shading.
  • feTile needs a tile to repeat. Make a small tile with a primitive subregion (for example an feFlood with its own width and height), and feTile fills the rest of the filter region with copies.
Posterize, find edges and light with filters

The first square collapses its smooth gradient into a few flat bands. The second keeps only the places where neighboring pixels differ (an edge-detection kernel; a smooth gradient has few edges, so it turns almost black). The circle gets a glossy highlight from a point light placed up and to the left of it.

Noise and distortion

feTurbulence creates a texture out of nothing: random, natural-looking noise (Perlin noise). baseFrequency sets the size of the detail (small numbers give large, smooth blobs), numOctaves adds finer layers of detail, and seed picks a different random pattern. type="fractalNoise" looks cloudy; type="turbulence" looks more like ripples.

On its own, noise looks like static. Its real strength appears when you feed it into feDisplacementMap, which moves every pixel of the source by an amount read from the noise's color channels. The result: wobbly hand-drawn lines, water reflections, heat haze or torn paper.

Turbulence and displacement

Turn scale up to 40 for a heavy distortion, or change seed to get a different wobble. Noise filters are expensive to compute, so keep them on small elements and avoid animating them on large areas.

Using SVG filters on HTML

Any SVG filter can style regular HTML too. Put a hidden SVG with the filter definitions somewhere in the page, then reference it from CSS:

HTML
<svg width="0" height="0" style="position: absolute" aria-hidden="true">
  <filter id="duotone">
    <feColorMatrix type="matrix" values="
      0.6 0.3 0.1 0 0.05
      0.3 0.4 0.1 0 0.10
      0.1 0.2 0.5 0 0.30
      0   0   0   1 0" />
  </filter>
</svg>

<img src="team.jpg" alt="Our team at the summer meetup" style="filter: url(#duotone)">

For everyday effects, the CSS shorthand functions (blur(), drop-shadow(), grayscale(), hue-rotate()) are simpler and are described in CSS Filters. They're actually built on the same SVG primitives; url(#id) is how you reach the ones CSS has no function for, such as turbulence and displacement.

Animating SVG with SMIL

SVG has its own animation elements, often called SMIL animation after the older standard they came from. You place an animation element inside the element it animates, and it changes one attribute over time:

  • <animate> changes any numeric or color attribute, such as r, x, opacity, fill or even a path's d.
  • <animateTransform> animates the transform attribute (type="rotate", scale, translate, skewX, skewY).
  • <animateMotion> moves an element along a path, optionally turning it to face the direction of travel with rotate="auto".
  • <set> switches an attribute to a value at a moment, without a transition.

The timing attributes are shared by all of them:

Attribute Meaning
attributeName Which attribute to change (not used by animateMotion)
from, to / values Start and end values, or a semicolon-separated list of keyframes
dur Length of one cycle, e.g. 2s or 500ms
begin When to start: 0s, 2s, click, otherId.click, otherId.end + 1s
repeatCount A number or indefinite
fill freeze keeps the final value; remove (default) jumps back
repeatDur Total time to keep repeating, such as 10s, instead of a count
keyTimes, calcMode, keySplines Fine control over timing and easing
keyPoints animateMotion only: how far along the path (0 to 1) the element is at each keyTimes moment
SMIL animation elements

Notice that rotate in animateTransform takes the center point too (0 170 70), so the square spins around its middle instead of the SVG's top-left corner. The click demo uses fill="freeze", so the orange dot stays where it stopped.

SMIL animations run in all current browsers, need no JavaScript, and work even when the SVG is loaded as an image with <img src="spinner.svg">, where scripts and outside CSS can't reach. That last point is their biggest advantage. From JavaScript, svgElement.pauseAnimations() and unpauseAnimations() stop and resume every SMIL animation in an SVG.

Animating SVG with CSS

Inline SVG elements are part of the DOM, so CSS animations and transitions work on them just like on HTML. CSS can animate transform, opacity and the SVG presentation properties such as fill, stroke, stroke-width and stroke-dashoffset.

Two details trip people up:

  • In SVG, a CSS transform-origin is measured from the SVG's own origin by default, not the element's center. Add transform-box: fill-box and transform-origin: center to spin or scale a shape around its middle.
  • The line-drawing effect uses dashes: set stroke-dasharray to the path's length (or any large number with pathLength="1"), then animate stroke-dashoffset from that length to 0.
CSS animation and reduced motion

pathLength="1" tells the browser to treat the whole path as 1 unit long, so stroke-dasharray: 1 and stroke-dashoffset: 1 hide it fully no matter its real length. That's why the zigzag "draws itself".

SMIL or CSS?

SMIL elements CSS animation
Works inside <img src="file.svg"> Yes Only if the CSS is inside the SVG file
Animate path shape (d) Yes Partly (browser support varies)
Move along a path animateMotion offset-path
Event triggers without JS begin="click", chaining with id.end :hover, :focus only
Respects prefers-reduced-motion Only with JavaScript Yes, with a media query
Familiar to most developers Less More

A good rule: use CSS for most interface animation (hover effects, spinners on inline SVG, line drawing) because it's familiar and easy to switch off. Use SMIL when the SVG must animate as a standalone file or image, or when you need to morph a shape or move along a curve.

Accessibility and performance

  • Motion can make people ill. Animations that spin, zoom or move across large areas can trigger dizziness for people with vestibular disorders. Wrap CSS animations in prefers-reduced-motion checks, and for SMIL call pauseAnimations() when matchMedia('(prefers-reduced-motion: reduce)').matches is true. Anything that moves for more than five seconds should be possible to pause.
  • Effects don't change meaning. A clipped, masked or blurred graphic still needs role="img" and a <title> if it carries information, as explained in SVG Paths, Text and Gradients.
  • Filters cost CPU and GPU time. Large blurs, turbulence and displacement are recalculated whenever the element repaints. Keep filtered areas small, and prefer animating transform and opacity, which browsers can handle cheaply.
  • IDs are page-global. Every clip path, mask and filter is found by id, so use distinctive names (this lesson uses an fx- prefix) to avoid clashes between inline SVGs.

Look up every element and attribute in the <svg> reference.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A shape inside a <clipPath> has fill="red" and opacity="0.5". How does that affect the clipped element?

    Clipping paths ignore paint and opacity. For partial transparency you need a mask.
  2. 2. In a default (luminance) <mask>, what does a black area in the mask do?

    With a luminance mask, white means fully visible, black means hidden and grays give partial transparency.
  3. 3. Your feDropShadow is cut off with a straight edge. What is the most likely fix?

    The default filter region is only 10% larger than the element on each side. Shadows and blurs that reach further get clipped.
  4. 4. How does feDisplacementMap know how far to move each pixel?

    in2 supplies a map image. xChannelSelector and yChannelSelector choose which channels control the horizontal and vertical shifts, multiplied by scale.
  5. 5. A rectangle spins around the corner of the SVG instead of its own center when you animate transform with CSS. What fixes it?

    For SVG elements, CSS transforms default to the SVG's own coordinate origin. fill-box makes the origin relative to the shape's bounding box.

Summary

  • <clipPath> cuts an element to a hard-edged outline; only the clip shapes' geometry counts. Use clipPathUnits="objectBoundingBox" for size-independent clips.
  • <mask> gives soft, partial visibility: white shows, black hides, grays are in between (or alpha with mask-type="alpha").
  • <filter> chains fe* primitives with in and result: blur, drop shadows, color matrices, merges, noise and displacement. Enlarge the filter region when effects get cut off.
  • SVG filters, clips and masks can style HTML elements through CSS filter, clip-path and mask with url(#id).
  • SMIL elements (animate, animateTransform, animateMotion, set) animate SVG without JavaScript, even inside <img>; CSS animations are easier to control and to switch off with prefers-reduced-motion.
  • Respect reduced-motion preferences, keep filtered areas small and give every effect a unique id.

Next: Canvas Basics, where you draw with JavaScript on a pixel surface instead of describing shapes in markup.