Home / Learn / How do I add a glowing trail that follows the mouse with Canvas?

How do I add a glowing trail that follows the mouse with Canvas?

A glowing trail that follows the pointer and fades is an effect portfolio and business sites like. We store the latest pointer positions, draw them as circles that shrink and fade over time, and stop the loop when nothing is left to draw.

Steps

  1. Put a full-screen canvas with position: fixed and pointer-events: none so it never blocks clicks underneath.
  2. Listen to pointermove, and add a point (x, y, life 1) on each move. Ignore pointerType === "touch" so touch scrolling is not affected.
  3. In requestAnimationFrame reduce each point life, remove expired points, and draw each point as a circle whose radius and opacity come from its life.
  4. Start the loop on the first move and stop it when the array is empty, so the canvas uses no resources while the pointer is still.
  5. Under prefers-reduced-motion do not enable the effect at all.

Sources

The code

HTML

<!doctype html>
<html lang="ar" dir="rtl">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
  body { margin: 0; min-height: 100vh; background: #020617; color: #fff; display: grid; place-items: center; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; }
  canvas { position: fixed; inset: 0; width: 100%; height: 100%; pointer-events: none; }   /* never blocks clicks */
</style>
<p>حرّك الماوس على الصفحة</p>
<canvas id="trail" aria-hidden="true"></canvas>
<script>
  const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
  if (!reduce) {                                                  // the whole effect is off for reduced motion
    const c = document.getElementById('trail'), ctx = c.getContext('2d');
    let dpr = 1, pts = [], raf = 0;
    const fit = () => { dpr = devicePixelRatio || 1; c.width = innerWidth * dpr; c.height = innerHeight * dpr; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); };
    fit(); addEventListener('resize', fit);
    addEventListener('pointermove', e => {
      if (e.pointerType === 'touch') return;                      // mouse and pen only, so scrolling by touch is untouched
      pts.push({ x: e.clientX, y: e.clientY, life: 1 });
      if (!raf) raf = requestAnimationFrame(frame);
    });
    function frame() {
      ctx.clearRect(0, 0, innerWidth, innerHeight);
      pts = pts.filter(p => (p.life -= 0.03) > 0);
      for (const p of pts) {
        ctx.beginPath(); ctx.arc(p.x, p.y, 10 * p.life, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(56,189,248,${p.life * .6})`; ctx.shadowColor = '#38bdf8'; ctx.shadowBlur = 16; ctx.fill();
      }
      raf = pts.length ? requestAnimationFrame(frame) : 0;        // stop the loop when nothing is left to draw
    }
    window.__trailPoints = () => pts.length;                       // test hook, safe to delete
  }
</script>
</html>

can't find the motion you need? Request it here

Related articles: