Motion path

Arrow shapes ride along a curve you can reshape by dragging its handles.

What you are seeing

A black curve crosses a light ground, with square magenta anchors, round magenta control handles and dashed lines joining each handle to its anchor. Several blue arrow shapes slide along the curve and turn to point where it is heading.

How it works

The route is a single path made of two cubic curves, so it needs seven points: three anchors and four control handles. Dragging any of them rewrites the d attribute right away.

Each rider is placed by asking the path for the point at a given length. To make it face along the curve, the script reads a second point one unit further on and turns the shape to the angle between them.

Riders are spaced evenly by adding an offset to their position along the length. The same maths is what the CSS offset-path property does, written out by hand so it works everywhere.

Source

/lab/motion-path/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Motion path</title>
<meta name="description" content="Shapes travel along an editable curve. Drag the handles to reshape the route.">
<link rel="stylesheet" href="../lab.css">
<style>
#route{fill:none;stroke:#24272c;stroke-width:2.5;stroke-linecap:round}
.arm{stroke:#8a909b;stroke-width:1.5;stroke-dasharray:3 3}
.pt{fill:#d4006a;stroke:#fff;stroke-width:2.5}
.pt.anchor{rx:2}
.rider{fill:#1f3fe0;stroke:#fff;stroke-width:2}
</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">Motion path</title>
      <desc id="d">A black curve made of two cubic segments with seven magenta handles. Blue arrow shapes ride along the curve and turn to face the direction of travel. Dragging a handle reshapes the curve and the riders follow the new route.</desc>
      <g id="arms"></g>
      <path id="route"/>
      <g id="riders"></g>
      <g id="handles"></g>
    </svg>
  </div>
  <div class="bar">
    <button id="play" type="button">Pause</button>
    <label><span>Speed</span><input id="speed" type="range" min="10" max="200" value="70"></label>
    <label><span>Riders</span><input id="count" type="range" min="1" max="6" value="3"></label>
    <label><input id="orient" type="checkbox" checked> <span>Face direction</span></label>
    <button id="reset" type="button">Reset path</button>
  </div>
  <p class="sr-only" id="hint">Handles: arrow keys move by 4, shift plus arrow moves by 16.</p>
</main>
<script src="../lab.js"></script>
<script src="demo.js"></script>
</body>
</html>
/lab/motion-path/demo.js
(function () {
  'use strict';
  var $ = Lab.$, svg = $('#svg'), route = $('#route'), arms = $('#arms'), riders = $('#riders'), hg = $('#handles');
  var start = [[40, 220], [70, 60], [170, 60], [200, 150], [230, 240], [330, 240], [360, 80]];
  var P = start.map(function (p) { return p.slice(); });
  var labels = ['Start anchor', 'Start control', 'Middle control in', 'Middle anchor', 'Middle control out', 'End control', 'End anchor'];
  var armLines = [[0, 1], [2, 3], [3, 4], [5, 6]].map(function (a) { return { a: a, el: Lab.make('line', { class: 'arm' }, arms) }; });
  var handles = P.map(function (p, i) {
    var anchor = i % 3 === 0;
    var h = anchor ? Lab.make('rect', { class: 'pt grab anchor', width: 18, height: 18, rx: 3 }, hg) : Lab.make('circle', { class: 'pt grab', r: 9 }, hg);
    h.setAttribute('tabindex', 0); h.setAttribute('role', 'button'); h.setAttribute('aria-describedby', 'hint');
    Lab.drag(h, { space: svg, move: function (pt) { P[i][0] = Lab.clamp(pt.x, 8, 392); P[i][1] = Lab.clamp(pt.y, 8, 292); draw(); } });
    h.addEventListener('keydown', function (e) {
      var s = e.shiftKey ? 16 : 4, d = { ArrowLeft: [-s, 0], ArrowRight: [s, 0], ArrowUp: [0, -s], ArrowDown: [0, s] }[e.key];
      if (!d) return;
      P[i][0] = Lab.clamp(P[i][0] + d[0], 8, 392); P[i][1] = Lab.clamp(P[i][1] + d[1], 8, 292); draw(); e.preventDefault();
    });
    return h;
  });
  var count = 0, riderEls = [];
  function setCount(n) {
    while (riderEls.length < n) riderEls.push(Lab.make('path', { class: 'rider', d: 'M12 0L-9 8L-5 0L-9 -8Z' }, riders));
    riderEls.forEach(function (r, i) { r.style.display = i < n ? '' : 'none'; });
    count = n;
  }
  function draw() {
    route.setAttribute('d', 'M' + P[0] + 'C' + P[1] + ' ' + P[2] + ' ' + P[3] + 'C' + P[4] + ' ' + P[5] + ' ' + P[6]);
    armLines.forEach(function (l) { l.el.setAttribute('x1', P[l.a[0]][0]); l.el.setAttribute('y1', P[l.a[0]][1]); l.el.setAttribute('x2', P[l.a[1]][0]); l.el.setAttribute('y2', P[l.a[1]][1]); });
    handles.forEach(function (h, i) {
      var off = i % 3 === 0 ? 9 : 0;
      h.setAttribute(i % 3 === 0 ? 'x' : 'cx', P[i][0] - off); h.setAttribute(i % 3 === 0 ? 'y' : 'cy', P[i][1] - off);
      h.setAttribute('aria-label', labels[i] + ', x ' + Math.round(P[i][0]) + ', y ' + Math.round(P[i][1]));
    });
    place();
  }
  var u = 0; // travel position in path lengths per second share, 0..1
  function place() {
    var len = route.getTotalLength(), orient = $('#orient').checked;
    for (var i = 0; i < count; i++) {
      var f = (u + i / count) % 1, L = f * len, p = route.getPointAtLength(L), q = route.getPointAtLength(Math.min(len, L + 1)), a = 0;
      if (orient) a = Math.atan2(q.y - p.y, q.x - p.x) * 180 / Math.PI;
      if (L + 1 > len) { var r = route.getPointAtLength(L - 1); a = orient ? Math.atan2(p.y - r.y, p.x - r.x) * 180 / Math.PI : 0; }
      riderEls[i].setAttribute('transform', 'translate(' + p.x.toFixed(1) + ' ' + p.y.toFixed(1) + ') rotate(' + a.toFixed(1) + ')');
    }
  }
  var play = $('#play');
  function setPlay(on) { play.textContent = on ? 'Pause' : 'Play'; if (on) loop.start(); else loop.stop(); }
  var loop = Lab.loop(function (dt) { u = (u + dt * $('#speed').value / 1000 * 1.2) % 1; place(); });
  play.addEventListener('click', function () { setPlay(!loop.running()); });
  $('#count').addEventListener('input', function (e) { setCount(+e.target.value); place(); });
  $('#orient').addEventListener('change', place);
  $('#reset').addEventListener('click', function () { P = start.map(function (p) { return p.slice(); }); draw(); });
  setCount(3); draw();
  if (Lab.reduced) { u = 0.3; place(); 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}}