How do you animate SVG, and why use it instead of a GIF?

SVG animations stay sharp at any size and weigh a few kilobytes. Line drawing animates stroke-dashoffset against stroke-dasharray, fills and colours use CSS transitions, shapes morph between paths that share the same number of points, and generative art such as flow fields is computed in JavaScript and drawn as SVG or canvas.

How to choose, performance and accessibility
  • Use Line Draw or Logo Draw to reveal a logo or an illustration, Animated Icons for interface feedback, and Perlin Flow Field or Geometric Tessellation as generative backgrounds.
  • Compared with a GIF, SVG is lighter, scalable and restylable in CSS.
  • Simplify complex paths, give meaningful graphics a title, and hide purely decorative ones from screen readers with aria-hidden.
  • Line Draw, Perlin Flow Field and Text Mask Video are free with their full code; the rest come with Premium.
Generator

Your SVGs, with volume

The effects below animate your SVGs flat. The SVG to 3D generator gives them thickness: drop your file, set the material and the edges, and the object spins. A PNG logo works too — it gets traced on the way in.

The preview and the image are free. The code comes for $4.90 (this generator, unlimited exports) or with lifetime access.

Open the generator

Line Draw

SVG path that progressively draws itself using stroke-dasharray and dashoffset.

CSS stroke-dasharray
Effect page →
View source code
HTML
<div class="fx-0599-root">
  <svg class="lnd-svg" viewBox="0 0 150 150" aria-hidden="true">
    <path class="lnd-path" pathLength="100" d="M20,75 L50,30 L80,60 L110,20 L130,50 M20,130 L60,90 L100,110 L130,80"/>
  </svg>
</div>
CSS
.fx-0599-root,.fx-0599-root *,.fx-0599-root *::before,.fx-0599-root *::after{box-sizing:border-box}
.fx-0599-root{--lnd-color:#6366f1;--lnd-stroke:3;--lnd-size:150px;--lnd-speed:3s;--lnd-repeat:infinite;--lnd-bg:rgb(26,26,36);--lnd-height:250px;display:flex;align-items:center;justify-content:center;width:100%;position:relative;color:#fff;font-family:sans-serif;height:var(--lnd-height);overflow:hidden;background:var(--lnd-bg)}
.fx-0599-root .lnd-svg{display:block;width:var(--lnd-size);max-width:100%;height:auto}
.fx-0599-root .lnd-path{fill:none;stroke:var(--lnd-color);stroke-width:var(--lnd-stroke);stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:100;stroke-dashoffset:0;animation:lndDraw var(--lnd-speed) ease var(--lnd-repeat) both}
@keyframes lndDraw{0%{stroke-dashoffset:100}45%,55%{stroke-dashoffset:0}to{stroke-dashoffset:-100}}
@media (prefers-reduced-motion:reduce){.fx-0599-root .lnd-path{animation:none}}
JavaScript
/* Pure CSS — no JavaScript required */

Logo Draw

Three-part logo drawn one element after another.

CSS Multi-layer

Morphing Shape

Shape morphing from diamond to circle, star and square.

SMIL Morphing

SVG Fill Animation

Bottle that fills up to an adjustable level and drains, on a loop.

CSS Clip-path

Animated Icons

Check mark and cross drawn stroke by stroke in their circle.

CSS Icons

Path Following

Element that follows a defined SVG path using animateMotion.

SMIL animateMotion

SVG Text Draw

Text whose outline draws itself then fills with color.

CSS Text

Pulse / Heartbeat

SVG heart with heartbeat animation and pulse wave rings.

CSS Pulse

Rotating Gears

Interlocking gears rotating in opposite directions.

CSS Rotation

Wave Path

Animated wavy line with gradient and motion effect.

SMIL Wave

Perlin Flow Field

Particles guided by a Perlin vector field.

Canvas Perlin Particles
Effect page →
View source code
HTML
<div class="fx-0609-root">
  <canvas class="pff-canvas" role="img" aria-label="Blue and violet particles following the currents of a Perlin noise field"></canvas>
</div>
CSS
.fx-0609-root,
.fx-0609-root * {
  box-sizing: border-box;
}

.fx-0609-root {
  position: relative;
  width: 100%;
  overflow: hidden;
  background: #0a0a0f;
}

/* Fixed height by default; --pff-height also accepts 100% inside a parent of known height */
.fx-0609-root .pff-canvas {
  display: block;
  width: 100%;
  height: var(--pff-height, 300px);
}
JavaScript
(function () {
  // Perlin Flow Field: each particle follows the direction given by 3D Perlin noise (x, y, time).
  var SCALE = 0.0035;        // size of the currents: smaller = wider currents
  var DRIFT = 0.00009;       // how fast the field changes (noise units per ms)
  var DENSITY = 480;         // one particle per 480 px² of area
  var TRAIL = 0.05;          // share of the picture erased on each frame (60 fps): smaller = longer trails
  var LIFE = 4000;           // average particle lifetime (ms) before it is reborn elsewhere
  var HUE = 220;             // starting hue (blue); particles range from HUE to HUE + 60

  var reduced = window.matchMedia ? window.matchMedia('(prefers-reduced-motion: reduce)') : null;

  // "Improved" Perlin noise (Ken Perlin, 2002): gradients on a 3D grid, smoothed interpolation.
  function createNoise() {
    var p = new Uint8Array(512), i, j, t;
    for (i = 0; i < 256; i++) p[i] = i;
    for (i = 255; i > 0; i--) { j = Math.floor(Math.random() * (i + 1)); t = p[i]; p[i] = p[j]; p[j] = t; }
    for (i = 0; i < 256; i++) p[i + 256] = p[i];
    function fade(t) { return t * t * t * (t * (t * 6 - 15) + 10); }
    function mix(a, b, t) { return a + t * (b - a); }
    function grad(h, x, y, z) {
      h &= 15;
      var u = h < 8 ? x : y;
      var v = h < 4 ? y : (h === 12 || h === 14 ? x : z);
      return ((h & 1) ? -u : u) + ((h & 2) ? -v : v);
    }
    return function (x, y, z) {
      var X = Math.floor(x), Y = Math.floor(y), Z = Math.floor(z);
      x -= X; y -= Y; z -= Z;
      X &= 255; Y &= 255; Z &= 255;
      var u = fade(x), v = fade(y), w = fade(z);
      var A = p[X] + Y, AA = p[A] + Z, AB = p[A + 1] + Z;
      var B = p[X + 1] + Y, BA = p[B] + Z, BB = p[B + 1] + Z;
      return mix(
        mix(mix(grad(p[AA], x, y, z), grad(p[BA], x - 1, y, z), u),
            mix(grad(p[AB], x, y - 1, z), grad(p[BB], x - 1, y - 1, z), u), v),
        mix(mix(grad(p[AA + 1], x, y, z - 1), grad(p[BA + 1], x - 1, y, z - 1), u),
            mix(grad(p[AB + 1], x, y - 1, z - 1), grad(p[BB + 1], x - 1, y - 1, z - 1), u), v),
        w);
    };
  }

  function init(root) {
    // One instance per root, even if the script is pasted several times on the page.
    if (root.hasAttribute('data-pff-ready')) return;
    root.setAttribute('data-pff-ready', '');
    var canvas = root.querySelector('.pff-canvas');
    var ctx = canvas && canvas.getContext ? canvas.getContext('2d') : null;
    if (!ctx) return;
    var noise = createNoise();
    var W = 0, H = 0, ratio = 0, time = Math.random() * 100;
    var particles = [], raf = 0, last = 0, visible = true;

    // A particle is reborn at a random spot: without this, they all end up in the same currents.
    function place(q) {
      q.x = Math.random() * W;
      q.y = Math.random() * H;
      q.life = LIFE * (0.5 + Math.random());
    }

    function seed() {
      var n = Math.max(60, Math.min(3000, Math.round(W * H / DENSITY)));
      particles = [];
      for (var i = 0; i < n; i++) {
        var q = { v: 0.5 + Math.random(), c: 'hsla(' + Math.round(HUE + Math.random() * 60) + ', 80%, 60%, 0.8)' };
        place(q);
        q.life *= Math.random();
        particles.push(q);
      }
    }

    function advance(dt) {
      var k = dt / 16.667;
      // Trails fade to transparency: the visible background is the root's (CSS).
      ctx.globalCompositeOperation = 'destination-out';
      ctx.fillStyle = 'rgba(0, 0, 0, ' + (1 - Math.pow(1 - TRAIL, k)) + ')';
      ctx.fillRect(0, 0, W, H);
      ctx.globalCompositeOperation = 'source-over';
      for (var i = 0; i < particles.length; i++) {
        var q = particles[i];
        var angle = noise(q.x * SCALE, q.y * SCALE, time) * Math.PI * 4;
        q.x += Math.cos(angle) * q.v * k;
        q.y += Math.sin(angle) * q.v * k;
        if (q.x < 0) q.x += W; else if (q.x > W) q.x -= W;
        if (q.y < 0) q.y += H; else if (q.y > H) q.y -= H;
        q.life -= dt;
        if (q.life <= 0) place(q);
        ctx.fillStyle = q.c;
        ctx.beginPath();
        ctx.arc(q.x, q.y, 1, 0, Math.PI * 2);
        ctx.fill();
      }
    }

    // Reduced motion: the field is frozen and the particles trace their streamlines once.
    function drawStill() {
      for (var i = 0; i < 160; i++) advance(16.667);
    }

    function loop(t) {
      var dt = last ? Math.min(t - last, 50) : 16.667;
      last = t;
      time += DRIFT * dt;
      advance(dt);
      raf = requestAnimationFrame(loop);
    }

    function stop() {
      if (raf) cancelAnimationFrame(raf);
      raf = 0;
    }

    function play() {
      if (raf || !W || !visible || (reduced && reduced.matches)) return;
      last = 0;
      raf = requestAnimationFrame(loop);
    }

    // Size read from the displayed area; nothing starts while it is 0 (closed tab or accordion).
    function resize(force) {
      var w = canvas.clientWidth, h = canvas.clientHeight;
      if (!w || !h) { stop(); return; }
      var r = window.devicePixelRatio || 1;
      if (force || w !== W || h !== H || r !== ratio) {
        W = w; H = h; ratio = r;
        canvas.width = Math.round(w * r);
        canvas.height = Math.round(h * r);
        ctx.setTransform(r, 0, 0, r, 0, 0);
        seed();
        if (reduced && reduced.matches) { stop(); drawStill(); }
      }
      play();
    }

    if (window.ResizeObserver) new ResizeObserver(function () { resize(false); }).observe(canvas);
    else window.addEventListener('resize', function () { resize(false); });
    if (window.IntersectionObserver) {
      new IntersectionObserver(function (entries) {
        visible = entries[entries.length - 1].isIntersecting;
        if (visible) play(); else stop();
      }).observe(canvas);
    }
    if (reduced && reduced.addEventListener) reduced.addEventListener('change', function () { stop(); resize(true); });
    resize(false);
  }

  document.querySelectorAll('.fx-0609-root').forEach(init);
})();

Geometric Tessellation

Geometric mosaic with staggered animations.

CSS Grid Pattern

Recursive Circles

Nested SVG circles: each one holds three more, breathing in turn.

SVG JS Recursive

Lissajous Curves

Harmonic curves in perpetual motion.

Canvas Math Curves

Voronoi Pattern

Voronoi diagram with gradients.

SVG JS Voronoi

Sine Wave Grid

Grid of dots animated in a sine wave pattern.

CSS JS Wave

Spirograph

Rotating rings creating hypnotic patterns.

CSS JS Rotation

Fractal Tree

Recursively generated fractal tree.

Canvas Fractal Recursive

Maze Generator

Maze generated with the recursive backtracking algorithm.

Canvas Algorithm Recursive

Cellular Automata

Conway's Game of Life - artificial life simulation.

Canvas Simulation Conway

PLAY

Text Mask Video

Heading filled with a real video, visible only inside the letters.

CSS Text Video
Effect page →
View source code
HTML
<div class="fx-0619-root">
  <div class="tmv-stage">
    <video class="tmv-video" data-tmv-demo autoplay muted loop playsinline aria-hidden="true" tabindex="-1"></video>
    <h2 class="tmv-text">PLAY</h2>
  </div>
</div>
CSS
.fx-0619-root,
.fx-0619-root *,
.fx-0619-root *::before,
.fx-0619-root *::after {
  box-sizing: border-box;
}

.fx-0619-root {
  /* Settings: text size, block background, colours of the fallback and the demo clip */
  --tmv-size: 4rem;
  --tmv-page: #0a0a0f;
  --tmv-height: 250px;
  --tmv-c1: #6366f1;
  --tmv-c2: #d946ef;
  --tmv-c3: #06b6d4;
  --tmv-c4: #f43f5e;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  min-height: var(--tmv-height);
  overflow: hidden;
  position: relative;
  background: var(--tmv-page);
  color: #fff;
  font-family: sans-serif;
}

/* The block melts into the page (screen mode: black disappears); under the video, a flowing gradient while it has no frame */
.fx-0619-root .tmv-stage {
  position: relative;
  max-width: 100%;
  overflow: hidden;
  background: #000;
  mix-blend-mode: screen;
}

.fx-0619-root .tmv-stage::before,
.fx-0619-root .tmv-video {
  position: absolute;
  inset: 2px;
  display: block;
  width: calc(100% - 4px);
  height: calc(100% - 4px);
  pointer-events: none;
}

.fx-0619-root .tmv-stage::before {
  content: "";
  background: linear-gradient(90deg, var(--tmv-c1), var(--tmv-c2), var(--tmv-c3), var(--tmv-c4), var(--tmv-c1)) 0 50% / 400% 100%;
  animation: tmvFlow 3s linear infinite;
}

.fx-0619-root .tmv-video {
  object-fit: cover;
}

/* White text on black, multiply mode: the video only stays visible inside the letters */
.fx-0619-root .tmv-text {
  position: relative;
  margin: 0;
  padding: .3em .45em;
  font-size: var(--tmv-size);
  font-weight: 900;
  line-height: 1;
  text-align: center;
  overflow-wrap: anywhere;
  color: #fff;
  background: #000;
  mix-blend-mode: multiply;
}

/* Light-page variant: modes swapped (white disappears) */
.fx-0619-root.tmv-light {
  --tmv-page: #fff;
}

.fx-0619-root.tmv-light .tmv-stage {
  background: #fff;
  mix-blend-mode: multiply;
}

.fx-0619-root.tmv-light .tmv-text {
  color: #000;
  background: #fff;
  mix-blend-mode: screen;
}

/* Video is playing: the fallback gradient stops; video failed: it is hidden and the gradient fills the text */
.fx-0619-root.tmv-playing .tmv-stage::before {
  animation: none;
}

.fx-0619-root.tmv-failed .tmv-video {
  visibility: hidden;
}

@keyframes tmvFlow {
  to {
    background-position: 400% 50%;
  }
}

@media (prefers-reduced-motion: reduce) {
  .fx-0619-root .tmv-stage::before {
    animation: none;
  }
}
JavaScript
(function () {
  var reduce = window.matchMedia ? window.matchMedia('(prefers-reduced-motion: reduce)') : null;
  function reduced() { return !!(reduce && reduce.matches); }

  // Locally generated demo clip (no file): remove data-tmv-demo and give the video a src
  function demoClip(root, video) {
    var canvas = document.createElement('canvas');
    if (!canvas.captureStream) return null;
    canvas.width = 480;
    canvas.height = 270;
    var ctx = canvas.getContext('2d');
    var style = getComputedStyle(root);
    var colors = ['--tmv-c1', '--tmv-c2', '--tmv-c3', '--tmv-c4'].map(function (v, i) {
      return style.getPropertyValue(v).trim() || ['#6366f1', '#d946ef', '#06b6d4', '#f43f5e'][i];
    });
    var t = 0, last = 0, raf = 0;
    function draw() {
      var w = canvas.width, h = canvas.height;
      ctx.globalCompositeOperation = 'source-over';
      ctx.fillStyle = colors[0];
      ctx.fillRect(0, 0, w, h);
      for (var i = 1; i < 4; i++) {
        var x = w * (0.5 + 0.45 * Math.sin(t * (0.35 + i * 0.12) + i * 1.9));
        var y = h * (0.5 + 0.45 * Math.cos(t * (0.45 + i * 0.1) + i * 2.4));
        var g = ctx.createRadialGradient(x, y, 0, x, y, h * 0.95);
        g.addColorStop(0, colors[i]);
        g.addColorStop(1, 'rgba(0,0,0,0)');
        ctx.fillStyle = g;
        ctx.fillRect(0, 0, w, h);
      }
      ctx.globalCompositeOperation = 'lighter';
      for (var k = 0; k < 3; k++) {
        var bx = ((t * 70 + k * 190) % (w + 160)) - 80;
        var beam = ctx.createLinearGradient(bx - 50, 0, bx + 50, 0);
        beam.addColorStop(0, 'rgba(255,255,255,0)');
        beam.addColorStop(0.5, 'rgba(255,255,255,0.28)');
        beam.addColorStop(1, 'rgba(255,255,255,0)');
        ctx.fillStyle = beam;
        ctx.fillRect(bx - 50, 0, 100, h);
      }
    }
    function loop(now) {
      var dt = last ? Math.min(50, now - last) : 16;
      last = now;
      t += dt / 1000;
      draw();
      raf = requestAnimationFrame(loop);
    }
    draw();
    video.srcObject = canvas.captureStream(30);
    return {
      start: function () { if (!raf) { last = 0; raf = requestAnimationFrame(loop); } },
      stop: function () { cancelAnimationFrame(raf); raf = 0; },
      still: function () { draw(); }
    };
  }

  function init(root) {
    if (root.dataset.tmvReady) return;
    root.dataset.tmvReady = '1';
    var video = root.querySelector('.tmv-video');
    if (!video) return;
    var clip = null;
    if (video.hasAttribute('data-tmv-demo') && !video.getAttribute('src') && !video.querySelector('source')) {
      clip = demoClip(root, video);
    }
    var auto = video.autoplay;
    var visible = true, heldOff = false;
    // tmv-playing class once a video frame is shown; reduced motion = first frame, frozen
    video.addEventListener('playing', function () {
      root.classList.add('tmv-playing');
      if (reduced()) video.pause();
    });
    video.addEventListener('play', function () { if (clip) clip.start(); });
    video.addEventListener('pause', function () { if (clip) clip.stop(); });
    video.addEventListener('emptied', function () { root.classList.remove('tmv-playing'); });
    // No playable source (missing file, unsupported format): tmv-failed class, the text keeps the gradient
    video.addEventListener('error', function () {
      setTimeout(function () {
        if (video.error || video.networkState === 3) {
          root.classList.remove('tmv-playing');
          root.classList.add('tmv-failed');
        }
      }, 0);
    }, true);
    video.addEventListener('canplay', function () {
      if (auto && visible && !heldOff && !reduced() && video.paused) {
        var c = video.play();
        if (c && c.catch) c.catch(function () {});
      }
    }, { once: true });

    function settle() {
      if (reduced()) {
        if (!root.classList.contains('tmv-playing')) {
          if (clip) clip.still();
          var p = video.play();
          if (p && p.catch) p.catch(function () {});
        } else {
          video.pause();
        }
      } else if (auto && visible) {
        var q = video.play();
        if (q && q.catch) q.catch(function () {});
      }
    }
    // Off screen the video pauses; an autoplaying video resumes when it comes back
    if ('IntersectionObserver' in window) {
      new IntersectionObserver(function (entries) {
        visible = entries[0].isIntersecting;
        if (!visible && !video.paused) { heldOff = auto; video.pause(); }
        else if (visible && heldOff) { heldOff = false; if (!reduced()) { var r = video.play(); if (r && r.catch) r.catch(function () {}); } }
      }).observe(root);
    }
    if (reduce && reduce.addEventListener) reduce.addEventListener('change', settle);
    settle();
  }

  function start() { document.querySelectorAll('.fx-0619-root').forEach(init); }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start);
  else start();
})();

Shape Clip Reveal

Content revealed through a circular shape on hover.

CSS Clip-path Hover

Image Mask Text

Image visible only through the text.

CSS Image Text

Circular Reveal

Circular mask that expands from the mouse position.

JS Clip-path Interactive

SVG Clip Path

Block clipped into a star by an SVG clipPath, tilting on hover.

SVG Clip-path Shape

Gradient Mask Fade

Radial gradient mask: the block's edges melt into the page.

CSS Mask Gradient

Moving Mask

Mask that follows the mouse movement.

JS Mask Mouse

Split Reveal

Two panels that part on hover to reveal the content beneath.

CSS Clip-path Split

Blob Mask

Organic blob shape used as an animated mask.

CSS SVG Mask Organic

Diagonal Clip

Diagonal clip-path animation with multiple layers.

CSS Clip-path Layers

Frequently Asked Questions

How to animate SVG line drawing in CSS? +

Use stroke-dasharray and stroke-dashoffset. Set dasharray to the total path length, dashoffset to the same value, then animate dashoffset to 0. The stroke draws progressively. Get the length with path.getTotalLength() in JS.

How to do SVG morphing? +

Morphing requires two paths with the same number of points. Animate the path's d attribute between the two shapes. In CSS, use a transition on d (supported in Chrome/Edge). In JS, use libraries like flubber or GSAP MorphSVG.

Are SVG animations better than GIFs? +

Yes. SVG is vector-based (sharp at any size), lightweight (a few KB vs hundreds of KB for a GIF), and controllable (pause, speed, colors via CSS). An animated SVG is 5-10x smaller than an equivalent GIF.

How to optimize SVG animation performance? +

Simplify paths (fewer points), use CSS for simple animations (transform, opacity), JS only for complex animations (morphing). Avoid looping animations on complex SVGs (>500 points).

Can SVG icons be animated on hover? +

Yes. Embed the SVG inline (not as img), then target internal elements (path, circle, rect) with CSS :hover on the parent. Animate stroke, fill, transform. This is the technique used by the best websites.

Similar Categories