Path draw

Draw a line on stroke by stroke with dash offsets, then scrub it with a slider or by dragging the pen.

What you are seeing

A long blue looping line draws itself over a pale grey copy of the same line on a light ground. A magenta pen dot sits at the end of the drawn part. Below the line a code readout shows the current stroke-dasharray and stroke-dashoffset values.

How it works

The draw-on effect uses a dashed stroke with one dash as long as the whole path and a gap of the same size. Moving the dash with stroke-dashoffset slides the visible part along the line, from hidden to fully drawn.

Setting pathLength to 100 makes the numbers independent of the real length, so progress is simply a number from 0 to 100. The pen dot is placed with getPointAtLength.

Dragging the pen works the other way round. The script samples points along the path, finds the one nearest the pointer and turns its index back into progress. The readout shows the live dashoffset value.

Source

/lab/path-draw/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Path draw</title>
<meta name="description" content="Draw an SVG stroke on with stroke-dasharray and stroke-dashoffset, and scrub it by hand.">
<link rel="stylesheet" href="../lab.css">
<style>
#guide{fill:none;stroke:#d5d8de;stroke-width:6;stroke-linecap:round;stroke-linejoin:round}
#ink{fill:none;stroke:#1f3fe0;stroke-width:6;stroke-linecap:round;stroke-linejoin:round}
#pen{fill:#d4006a;stroke:#fff;stroke-width:3}
.code{font:12px ui-monospace,Menlo,Consolas,monospace;fill:#24272c}
</style>
</head>
<body>
<main class="demo">
  <div class="stage">
    <svg id="svg" class="drag-surface" viewBox="0 0 400 300" role="img" aria-labelledby="t d">
      <title id="t">Path draw</title>
      <desc id="d">A looping blue line draws itself across a light grey guide. A magenta pen dot marks the end of the drawn part and can be dragged along the line. A readout shows the current stroke-dashoffset value.</desc>
      <path id="guide" d="M30 190 C50 60 120 40 130 110 S100 215 160 185 S200 60 245 110 S275 215 315 165 S350 80 372 120"/>
      <path id="ink" pathLength="100" d="M30 190 C50 60 120 40 130 110 S100 215 160 185 S200 60 245 110 S275 215 315 165 S350 80 372 120"/>
      <circle id="pen" class="grab" r="11" cx="30" cy="190" tabindex="0" role="slider" aria-label="Pen position along the path" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"/>
      <text id="code" class="code" x="200" y="280" text-anchor="middle"></text>
    </svg>
  </div>
  <div class="bar">
    <button id="play" type="button">Pause</button>
    <label><span>Scrub</span><input id="scrub" type="range" min="0" max="1000" value="0" aria-label="Scrub drawing progress"></label>
    <label><span>Width</span><input id="w" type="range" min="2" max="14" value="6"></label>
    <label><input id="loop" type="checkbox" checked> <span>Loop</span></label>
  </div>
</main>
<script src="../lab.js"></script>
<script src="demo.js"></script>
</body>
</html>
/lab/path-draw/demo.js
(function () {
  'use strict';
  var $ = Lab.$, ink = $('#ink'), guide = $('#guide'), pen = $('#pen'), scrub = $('#scrub'), play = $('#play'), code = $('#code'), svg = $('#svg');
  var len = ink.getTotalLength(), N = 300, samples = [];
  for (var i = 0; i <= N; i++) { var p = ink.getPointAtLength(len * i / N); samples.push([p.x, p.y]); }
  ink.style.strokeDasharray = '100';
  var p = 0, dir = 1, hold = 0;

  function render() {
    var off = 100 - p * 100;
    ink.style.strokeDashoffset = off.toFixed(2);
    ink.style.opacity = p <= 0.001 ? 0 : 1;
    var pt = ink.getPointAtLength(len * p);
    pen.setAttribute('cx', pt.x.toFixed(1)); pen.setAttribute('cy', pt.y.toFixed(1));
    scrub.value = Math.round(p * 1000);
    var pct = Math.round(p * 100);
    pen.setAttribute('aria-valuenow', pct); scrub.setAttribute('aria-valuetext', pct + ' percent drawn');
    code.textContent = 'stroke-dasharray: 100; stroke-dashoffset: ' + off.toFixed(1);
  }
  function setPlay(on) { play.textContent = on ? 'Pause' : 'Play'; if (on) loop.start(); else loop.stop(); }
  var loop = Lab.loop(function (dt) {
    if (hold > 0) { hold -= dt; return; }
    p += dt / 4.5;
    if (p >= 1) {
      p = 1; render();
      if ($('#loop').checked) { hold = 1; p = 0; } else setPlay(false);
      return;
    }
    render();
  });
  play.addEventListener('click', function () { setPlay(!loop.running()); });
  scrub.addEventListener('input', function () { p = scrub.value / 1000; setPlay(false); render(); });
  $('#w').addEventListener('input', function (e) { ink.style.strokeWidth = guide.style.strokeWidth = e.target.value + 'px'; });
  Lab.drag(pen, {
    space: svg,
    down: function () { setPlay(false); },
    move: function (pt) {
      var best = 0, bd = 1e9;
      for (var i = 0; i <= N; i++) { var dx = samples[i][0] - pt.x, dy = samples[i][1] - pt.y, d = dx * dx + dy * dy; if (d < bd) { bd = d; best = i; } }
      p = best / N; render();
    }
  });
  pen.addEventListener('keydown', function (e) {
    var step = e.shiftKey ? 0.1 : 0.01, k = e.key;
    if (k === 'ArrowRight' || k === 'ArrowUp') p += step;
    else if (k === 'ArrowLeft' || k === 'ArrowDown') p -= step;
    else if (k === 'Home') p = 0; else if (k === 'End') p = 1; else return;
    p = Lab.clamp(p, 0, 1); setPlay(false); render(); e.preventDefault();
  });
  render();
  if (Lab.reduced) { p = 0.62; render(); setPlay(false); } else setPlay(true);
})();
/lab/lab.js
/* Small shared helpers for the SVG Wow! lab demos. No dependencies. */
(function () {
  'use strict';
  var NS = 'http://www.w3.org/2000/svg';
  var mq = window.matchMedia('(prefers-reduced-motion: reduce)');
  var Lab = (window.Lab = { NS: NS });
  Object.defineProperty(Lab, 'reduced', { get: function () { return mq.matches; } });
  Lab.$ = function (s, r) { return (r || document).querySelector(s); };
  Lab.$$ = function (s, r) { return Array.prototype.slice.call((r || document).querySelectorAll(s)); };
  Lab.clamp = function (v, a, b) { return Math.max(a, Math.min(b, v)); };
  Lab.lerp = function (a, b, t) { return a + (b - a) * t; };
  Lab.ease = function (t) { return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; };
  Lab.make = function (tag, attrs, parent) {
    var e = document.createElementNS(NS, tag);
    if (attrs) for (var k in attrs) e.setAttribute(k, attrs[k]);
    if (parent) parent.appendChild(e);
    return e;
  };
  /* Client point to the user space of `el` (any SVG graphics element). */
  Lab.pt = function (el, evt) {
    var m = el.getScreenCTM();
    if (!m) return { x: 0, y: 0 };
    var p = new DOMPoint(evt.clientX, evt.clientY).matrixTransform(m.inverse());
    return { x: p.x, y: p.y };
  };
  /* requestAnimationFrame loop that pauses while the document is hidden. */
  Lab.loop = function (fn) {
    var raf = 0, last = 0, running = false, wanted = false, self = {};
    function tick(t) {
      if (!running) return;
      raf = requestAnimationFrame(tick);
      var dt = last ? Math.min((t - last) / 1000, 0.1) : 0;
      last = t;
      fn(dt, t / 1000);
    }
    function go() { if (running || document.hidden || !wanted) return; running = true; last = 0; raf = requestAnimationFrame(tick); }
    function halt() { running = false; cancelAnimationFrame(raf); }
    self.start = function () { wanted = true; go(); };
    self.stop = function () { wanted = false; halt(); };
    self.running = function () { return wanted; };
    document.addEventListener('visibilitychange', function () { if (document.hidden) halt(); else go(); });
    return self;
  };
  /* Pointer drag with capture. space: element whose user space the points use. */
  Lab.drag = function (el, o) {
    var active = false, space = o.space || el.ownerSVGElement || el;
    el.addEventListener('pointerdown', function (e) {
      if (e.button > 0) return;
      active = true;
      try { el.setPointerCapture(e.pointerId); } catch (_) {}
      if (o.down) o.down(Lab.pt(space, e), e);
      e.preventDefault();
    });
    el.addEventListener('pointermove', function (e) { if (active) o.move(Lab.pt(space, e), e); });
    function end(e) {
      if (!active) return;
      active = false;
      try { el.releasePointerCapture(e.pointerId); } catch (_) {}
      if (o.up) o.up(e);
    }
    el.addEventListener('pointerup', end);
    el.addEventListener('pointercancel', end);
  };
  Lab.say = function (msg) {
    var l = document.getElementById('live');
    if (l) l.textContent = msg;
  };
})();
/lab/lab.css
:root{--bg:#f1f2f4;--ink:#24272c;--blue:#1f3fe0;--mag:#d4006a;--line:#c9ccd3;--panel:#fff;--muted:#555b66;font-family:system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}
*{box-sizing:border-box}
html,body{margin:0;height:100%;background:var(--bg);color:var(--ink);overflow-x:hidden}
body{font-size:13px;line-height:1.3}
.demo{display:flex;flex-direction:column;height:100%;min-height:0}
.stage{flex:1 1 auto;min-height:120px;position:relative;overflow:hidden;background:var(--bg)}
.stage>svg{position:absolute;left:0;top:0;width:100%;height:100%;display:block}
.bar{flex:0 0 auto;display:flex;flex-wrap:wrap;gap:6px 14px;align-items:center;padding:6px 10px;background:var(--panel);border-top:1px solid var(--line);max-height:46%;overflow:auto}
.bar .grp{display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px}
label{display:inline-flex;align-items:center;gap:6px;white-space:nowrap}
label>span,.dim{color:var(--muted)}
output{font-variant-numeric:tabular-nums;min-width:3.2ch;display:inline-block}
button,select,input[type=number],input[type=text]{font:inherit;color:var(--ink);background:#fff;border:1px solid #8a909b;border-radius:6px;padding:3px 8px;min-height:28px}
button{border-color:var(--ink);cursor:pointer}
button:hover{background:#e7e9ef}
button[aria-pressed=true]{background:var(--ink);color:#fff}
input[type=range]{width:110px;accent-color:var(--blue);margin:0}
input[type=color]{width:34px;height:28px;padding:1px;border:1px solid #8a909b;border-radius:6px;background:#fff}
input[type=checkbox]{accent-color:var(--blue);width:16px;height:16px}
:focus-visible{outline:3px solid var(--blue);outline-offset:2px}
.grab{cursor:grab;touch-action:none}
.grab:active{cursor:grabbing}
.grab:focus-visible{outline:none;stroke:var(--blue);stroke-width:4px}
.drag-surface{touch-action:none}
.ro{font-size:11px;color:var(--muted)}
.sr-only{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
svg text{font-family:inherit}
pre,textarea{font:11px/1.35 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
@media (pointer:coarse){button,select,input[type=number]{min-height:38px}input[type=range]{height:30px}}
@media (max-width:420px){.bar{gap:6px 10px;padding:6px 8px}input[type=range]{width:96px}}
@media (min-width:700px){.demo.split{flex-direction:row}.demo.split .stage{flex:1 1 auto}.demo.split .bar{width:320px;max-height:none;flex:0 0 320px;border-top:0;border-left:1px solid var(--line);align-content:flex-start}}