Skip to content

176 web animation techniques, each a live demo with plain settings and a ready-made prompt for your AI assistant. No dependencies, no build step.

34.0 KB
Raw Blame
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>SVG Path Animation — Animation Handbook</title>
  <meta name="description" content="A line drawing draws itself, stroke by stroke. Best for icons and logos.">
  <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/svg-path-animation/">
  <link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png">
  <link rel="icon" type="image/svg+xml" href="../../../favicon.svg">
  <link rel="apple-touch-icon" href="../../../apple-touch-icon.png">
  <meta property="og:type" content="article">
  <meta property="og:site_name" content="Animation Handbook">
  <meta property="og:title" content="SVG Path Animation — Animation Handbook">
  <meta property="og:description" content="A line drawing draws itself, stroke by stroke. Best for icons and logos.">
  <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/svg-path-animation/">
  <meta property="og:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:title" content="SVG Path Animation — Animation Handbook">
  <meta name="twitter:description" content="A line drawing draws itself, stroke by stroke. Best for icons and logos.">
  <meta name="twitter:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
  <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "SVG Path Animation", "name": "SVG Path Animation", "description": "A line drawing draws itself, stroke by stroke. Best for icons and logos.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/svg-path-animation/", "inLanguage": "en", "articleSection": "3D & Advanced", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, 3D & Advanced, SVG Path Animation"}</script>
  <style>
    :root{--ui-accent:#3fd6c4;--stroke-w:2;--stroke-color:#58a6ff;--fill-dur:400ms}
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    .stage{position:relative;display:flex;align-items:center;justify-content:center;padding:24px;background:#04060c}
    /* max-height keeps the whole drawing inside a short stage (the box is 400 x 260 at full size) */
    .stage svg{width:100%;max-width:400px;max-height:100%;overflow:visible}
    /* transparent, not none: a fill can only fade in from a color */
    .draw-path{
      fill:transparent;fill-opacity:.15;stroke:var(--stroke-color);stroke-width:var(--stroke-w);
      stroke-linecap:round;stroke-linejoin:round;
      stroke-dasharray:1;stroke-dashoffset:1;
    }
    .draw-path.fill-done{fill:var(--stroke-color);transition:fill var(--fill-dur) ease}
    @media(prefers-reduced-motion:reduce){.draw-path{stroke-dashoffset:0!important;transition:none!important}}
    /* See inside and Compare: all of it stays hidden in Normal. Labels are plain words on a dark backing, above every moving part. */
    .copy,.io,.io-routes,.cap{display:none}
    .cap{position:absolute;z-index:3;padding:3px 8px;border-radius:6px;background:rgba(4,6,12,.92);border:1px solid rgba(244,244,242,.2);
      color:#f4f4f2;font:600 13px/1.3 var(--hb-font)}
    .cap-a,.cap-b,.cap-c{text-wrap:balance}
    .cap-fill,.cap-h1,.cap-h2,.cap-pose{white-space:nowrap}
    .cap-a{left:8px;top:8px;max-width:calc(54% - 12px)}
    .cap-b{right:8px;top:8px;max-width:calc(46% - 12px)}
    .cap-c{left:8px;bottom:8px;max-width:calc(100% - 16px)}
    .cap-fill{padding:0 6px;font-size:12px;line-height:14px}
    .caps{display:contents}
    .ph{display:none}
    .io{position:absolute;inset:0;z-index:2;pointer-events:none}
    .stage .io-over{position:absolute;inset:0;width:100%;height:100%;max-width:none;max-height:none}
    .io-routes path{fill:none;stroke:var(--stroke-color);stroke-opacity:.6;stroke-width:var(--stroke-w);stroke-dasharray:6 6}
    .io-over text{font:700 12px/1 var(--hb-font);fill:#f4f4f2;text-anchor:middle;dominant-baseline:central}
    .io-over .bar{fill:var(--stroke-color)}
    .io-over .fillbar{fill-opacity:.3;stroke:var(--stroke-color);stroke-width:1.5}
    .io-over .axis{fill:none;stroke:rgba(244,244,242,.5)}
    .io-over .mk{fill:#f4f4f2}
    .io-over .lead{fill:none;stroke:#f4f4f2;stroke-width:1}
    .io-over .dot{fill:#04060c;stroke:#f4f4f2;stroke-width:1.5}
    .io-over .tip{fill:#f4f4f2;stroke:var(--ui-accent);stroke-width:2.5}
    /* See inside: the drawing shrinks to make room for the words above it and the time line under it (the script sets the room). */
    .stage[data-hb-mode="inside"]{padding:var(--io-t,50px) 24px var(--io-b,110px)}
    .stage[data-hb-mode="inside"] .io,.stage[data-hb-mode="inside"] .cap-in{display:block}
    .stage[data-hb-mode="inside"] .io-routes{display:inline}
    /* Compare: the finished drawing on the left, the real one on the right, side by side at every width. A copy at rest rests part
       way through its draw (the script poses it), with the rest of each line faint and its own words under it. */
    .stage[data-hb-mode="compare"]{padding:48px 12px 44px;gap:12px}
    .stage[data-hb-mode="compare"]::after{content:'';position:absolute;top:0;bottom:0;left:50%;border-left:1px solid rgba(244,244,242,.14)}
    .stage[data-hb-mode="compare"] .copy{display:contents}
    .stage[data-hb-mode="compare"] .copy svg{order:-1}
    .stage[data-hb-mode="compare"] svg{flex:1 1 0;width:auto;min-width:0}
    .stage[data-hb-mode="compare"] .cap-cmp{display:block;transform:translateX(-50%)}
    .cap-h1{left:calc(12px + (100% - 36px)/4);top:10px}
    .cap-h2{left:calc(24px + (100% - 36px)*.75);top:10px}
    .cap-pose{left:calc(24px + (100% - 36px)*.75);bottom:10px;visibility:hidden}
    .stage[data-hb-mode="compare"].posed .cap-pose{visibility:visible}
    .stage[data-hb-mode="compare"].posed .io-routes{display:inline}
    /* A posed line: its dash is set from a variable, which also beats the reduced-motion rule above */
    .stage[data-hb-mode="inside"] .draw-path.pose,.stage[data-hb-mode="compare"] .draw-path.pose{stroke-dashoffset:var(--po)!important;transition:none!important}
    @media(max-width:600px){
      .stage[data-hb-mode="inside"] .cap-b{display:none}
      .stage[data-hb-mode="inside"] .ph{display:inline}
      .cap-a{max-width:calc(100% - 16px)}
    }
  </style>
  <link rel="stylesheet" href="../../../assets/css/demo-page.css?v=11">
  <script src="../../../assets/js/demo-page.js?v=11" defer></script>
</head>
<body class="hb" data-hb-kind="once" data-hb-autoplay>
<nav class="hb-bar" aria-label="Animation Handbook">
  <a class="hb-home" href="../../../"><svg class="hb-mark" viewBox="0 0 32 32" aria-hidden="true"><g class="g"><circle cx="11.16" cy="20.84" r="6.1"/><circle cx="15.12" cy="16.88" r="6.1"/><circle cx="18.51" cy="13.49" r="6.1"/></g><circle class="b" cx="21.2" cy="10.8" r="6.6"/></svg><span>Animation Handbook</span></a>
  <span class="hb-pager"><a href="../noise-based-motion/" rel="prev" aria-label="Previous: Noise-Based Motion"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg><span><span class="hb-dir">Previous: </span>Noise-Based Motion</span></a><a href="../chromatic-aberration/" rel="next" aria-label="Next: Chromatic Aberration"><span><span class="hb-dir">Next: </span>Chromatic Aberration</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m9 18 6-6-6-6"/></svg></a></span>
  <a class="hb-star" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener" aria-label="Star on GitHub"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg><span>Star on GitHub</span></a>
</nav>
<main class="hb-page">
  <header class="hb-head">
    <p class="hb-cat">06.09 · 3D &amp; Advanced</p>
    <h1>SVG Path Animation</h1>
    <p class="hb-lede">A line drawing draws itself, stroke by stroke. Best for icons and logos.</p>
  </header>

  <section class="hb-step hb-watch" aria-labelledby="hb-watch-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">1</span>
      <div><h2 id="hb-watch-title">Watch it</h2><p>It plays by itself. Turn on slow motion to see each part of the movement.</p></div>
    </div>
    <div class="seg hb-modes" role="group" aria-label="What the box shows" data-hb-modes>
      <button type="button" data-hb-mode="normal" class="on" aria-pressed="true">Normal</button>
      <button type="button" data-hb-mode="inside" aria-pressed="false">See inside</button>
      <button type="button" data-hb-mode="compare" aria-pressed="false">Compare</button>
    </div>
    <div class="stage hb-dots">
      <svg id="svg-stage" viewBox="0 0 400 260" role="img" aria-label="House and star icon">
        <g class="io-routes"></g>
        <g id="drawing-group"></g>
      </svg>
      <div class="copy" inert aria-hidden="true"><svg viewBox="0 0 400 260"><g></g></svg></div>
      <div class="io" aria-hidden="true"><svg class="io-over"></svg></div>
      <div class="caps" aria-hidden="true">
        <span class="cap cap-in cap-a" data-hb-caption>Faint: each whole line, hidden by its dash<span class="ph"> · 1, 2, 3: the order they draw in</span></span>
        <span class="cap cap-in cap-b" data-hb-caption>1, 2, 3: the order they draw in</span>
        <span class="cap cap-in cap-c" data-hb-caption></span>
        <span class="cap cap-in cap-fill" data-hb-caption>Fill</span>
        <span class="cap cap-cmp cap-h1" data-hb-caption>Already there</span>
        <span class="cap cap-cmp cap-h2" data-hb-caption>Draws itself</span>
        <span class="cap cap-cmp cap-pose" data-hb-caption>One second in</span>
      </div>
    </div>
    <div class="hb-player">
      <button class="hb-play" type="button" id="btn-play" data-hb-replay><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/></svg>Replay</button>
      <label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="loop-tog" data-hb-loop autocomplete="off"><span>Loop</span></label>
      <label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="slow-tog" data-hb-slowmo autocomplete="off"><span>Slow motion</span></label>
    </div>
    <div class="hb-mode-notes" aria-live="polite">
      <p data-hb-for="inside" hidden>Inside, each line is all there from the start, hidden by a dash as long as the line; sliding the dash away uncovers it from the dot, in the numbered order.</p>
      <p data-hb-for="compare" hidden>Already there shows the finished drawing at once. Draws itself uncovers each line from one end, as if drawn by hand.</p>
    </div>
  </section>

  <section class="hb-step hb-try" aria-labelledby="hb-try-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">2</span>
      <div><h2 id="hb-try-title">Try it</h2><p>Change a setting and the animation plays again.</p></div>
    </div>
    <div class="hb-settings">
      <div class="hb-setting">
        <p class="hb-setting-name" id="drawing-lbl">Drawing</p>
        <div class="seg" id="drawing-seg" role="group" aria-labelledby="drawing-lbl">
          <button type="button" data-drawing="0" class="on" aria-pressed="true">Icon</button>
          <button type="button" data-drawing="1" aria-pressed="false">Signature</button>
          <button type="button" data-drawing="2" aria-pressed="false">Logo</button>
        </div>
        <p class="hb-hint">What is drawn: an icon, a signature or a logo.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="speed-lbl">Speed</p>
        <div class="seg" id="speed-seg" role="group" aria-labelledby="speed-lbl">
          <button type="button" data-ms="2400" aria-pressed="false">Slow</button>
          <button type="button" data-ms="1500" class="on" aria-pressed="true">Normal</button>
          <button type="button" data-ms="900" aria-pressed="false">Fast</button>
        </div>
        <p class="hb-hint">How long each line takes to draw.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="width-lbl">Line thickness</p>
        <div class="seg" id="width-seg" role="group" aria-labelledby="width-lbl">
          <button type="button" data-w="1" aria-pressed="false">Thin</button>
          <button type="button" data-w="2" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-w="4" aria-pressed="false">Thick</button>
        </div>
        <p class="hb-hint">Thin looks precise; thick looks bold.</p>
      </div>
    </div>
    <details class="hb-options">
      <summary><span class="hb-more-label">More options</span><span class="hb-less">Fewer options</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg></summary>
      <div class="hb-settings">
        <div class="hb-setting">
          <p class="hb-setting-name" id="feel-lbl">Feel</p>
          <div class="seg" id="feel-seg" role="group" aria-labelledby="feel-lbl">
            <button type="button" data-ease="ease-out" class="on" aria-pressed="true">Smooth</button>
            <button type="button" data-ease="ease-in-out" aria-pressed="false">Gentle</button>
            <button type="button" data-ease="linear" aria-pressed="false">Even</button>
          </div>
          <p class="hb-hint">Smooth slows at the end, like a hand finishing.</p>
        </div>
        <div class="hb-setting">
          <p class="hb-setting-name" id="color-lbl">Line color</p>
          <div class="swatches" id="color-sw" role="group" aria-labelledby="color-lbl">
            <button type="button" aria-pressed="false" aria-label="Pink" data-color="#ff6f8b" style="background:#ff6f8b"></button>
            <button type="button" aria-pressed="false" aria-label="White" data-color="#f4f4f2" style="background:#f4f4f2"></button>
            <button type="button" class="on" aria-pressed="true" aria-label="Blue" data-color="#58a6ff" style="background:#58a6ff"></button>
            <button type="button" aria-pressed="false" aria-label="Purple" data-color="#d2a8ff" style="background:#d2a8ff"></button>
            <button type="button" aria-pressed="false" aria-label="Green" data-color="#56d364" style="background:#56d364"></button>
            <button type="button" aria-pressed="false" aria-label="Orange" data-color="#ffa657" style="background:#ffa657"></button>
          </div>
          <p class="hb-hint">The color of the lines.</p>
        </div>
        <div class="hb-setting">
          <label class="hb-switch-row"><span>Starts from the other end</span><input class="hb-switch" type="checkbox" role="switch" id="rev-tog" autocomplete="off"></label>
          <p class="hb-hint">Draws each line from its end back to its start.</p>
        </div>
        <div class="hb-setting">
          <label class="hb-switch-row"><span>Fills in at the end</span><input class="hb-switch" type="checkbox" role="switch" id="fill-tog" autocomplete="off"></label>
          <p class="hb-hint">Fills the shapes once the lines are drawn.</p>
        </div>
      </div>
    </details>
  </section>

  <section class="hb-step hb-prompt-step" aria-labelledby="hb-prompt-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">3</span>
      <div><h2 id="hb-prompt-title">Copy the prompt</h2><p>Paste it into an AI assistant such as ChatGPT, Claude or Cursor to build this in your own project.</p></div>
    </div>
    <div class="hb-card">
      <p class="hb-prompt">Add a self-drawing line to [your icon, logo or signature, drawn as SVG lines]. Measure the length of each line, hide it behind a dash exactly as long as the line, then slide the dash away so the line appears from one end to the other, as if drawn by hand. Draw several lines one after another, each starting a little after the one before. When the settings include it, fill the shapes once the lines are done. The finished drawing should be there for screen readers from the start. If the visitor has reduced motion turned on, show the drawing complete. Match the settings listed below.</p>
      <div class="hb-chips-box" hidden>
        <p class="hb-chips-title">Your settings</p>
        <ul class="hb-chips"></ul>
      </div>
      <div class="hb-copy-row">
        <button class="hb-copy" type="button"><svg class="hb-ic hb-i-copy" viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg><svg class="hb-ic hb-i-done" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg><span class="hb-copy-label" aria-live="polite">Copy prompt</span></button>
        <p class="hb-hint">Replace the words in brackets with your own element. Your settings are added at the end.</p>
      </div>
    </div>
    <div class="hb-star-row"><p>Free and open source. If this helped, a star on GitHub helps other people find it.</p><a class="hb-star-btn" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg>Star on GitHub</a></div>
  </section>

  <section class="hb-about" aria-labelledby="hb-what-title">
    <div class="hb-what">
      <h2 id="hb-what-title">What it is</h2>
      <div class="hb-what-text"><p>The full explanation is in <a href="README.md">README.md</a>.</p></div>
    </div>
    <div class="hb-fit">
      <h2>Good for</h2>
      <ul class="hb-tags hb-good"><li>Icons</li><li>Logos</li><li>Signatures</li><li>Illustrations</li></ul>
      <h3>Avoid on</h3>
      <ul class="hb-tags hb-avoid"><li>Photos</li><li>Body text</li></ul>
    </div>
  </section>

  <section class="hb-related" aria-labelledby="hb-related-title" hidden>
    <h2 id="hb-related-title">Similar animations</h2>
    <div class="hb-rel-list"></div>
  </section>
</main>
<footer class="hb-foot"><span>Animation Handbook</span><a href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener">Source on GitHub</a><a href="#top">Back to top ↑</a></footer>
<script>
  const DRAWINGS=[
    {label:'House and star icon',paths:[
      'M 60 200 L 60 120 L 200 40 L 340 120 L 340 200 Z',
      'M 160 200 L 160 150 L 240 150 L 240 200',
      'M 200 40 L 215 80 L 260 80 L 225 105 L 240 148 L 200 122 L 160 148 L 175 105 L 140 80 L 185 80 Z'
    ]},
    {label:'Signature',paths:[
      'M 30 180 C 40 160 60 140 80 150 C 100 160 90 190 110 180 C 130 170 120 140 145 145 C 165 150 160 175 180 170 C 195 165 190 145 210 148 C 230 151 225 178 250 172 C 270 167 265 140 290 145 C 310 150 310 175 340 170 C 360 166 365 140 380 145'
    ]},
    {label:'Logo mark',paths:[
      'M 200 10 A 120 120 0 1 1 199.99 10',
      'M 200 80 L 240 150 L 200 130 L 160 150 Z',
      'M 200 130 L 200 185'
    ]}
  ];
  const svg=document.getElementById('svg-stage');
  const group=document.getElementById('drawing-group');
  const vars=document.documentElement.style;
  const loopTog=document.getElementById('loop-tog'),slowTog=document.getElementById('slow-tog');
  const revTog=document.getElementById('rev-tog'),fillTog=document.getElementById('fill-tog');
  const motionOk=!window.matchMedia('(prefers-reduced-motion:reduce)').matches;
  let current=0,dur=1500,ease='ease-out',timers=[];
  // See inside and Compare. The Feel choices as the four numbers of their speed curves (the browser's own); sizes in pixels: the numbered
  // dots (their largest radius; a small drawing gets smaller ones), the pen tip, a bar and the pitch of the bars, the gaps, and how far a dot
  // may stray past the drawing's box.
  const stage=document.querySelector('.stage'),NS='http://www.w3.org/2000/svg';
  const CURVES={'ease-out':[0,0,.58,1],'ease-in-out':[.42,0,.58,1],linear:[0,0,1,1]};
  const DOT_R=10,TIP_R=5,ROW=7,PITCH=14,PAD=8,GAP=10,SLACK=4;
  const MORE={inside:", each line's whole route faint, with its start dot, its order number and a bar for its drawing time",compare:', drawing itself'};
  const over=stage.querySelector('.io-over'),routes=svg.querySelector('.io-routes'),copyG=stage.querySelector('.copy g');
  const capA=stage.querySelector('.cap-a'),capB=stage.querySelector('.cap-b'),capC=stage.querySelector('.cap-c');
  const capFill=stage.querySelector('.cap-fill'),capPose=stage.querySelector('.cap-pose'),capPh=capA.querySelector('.ph');
  const notes={inside:document.querySelector('[data-hb-for="inside"]'),compare:document.querySelector('[data-hb-for="compare"]')};
  // built: the lines of the last play; running: a play or its hold is under way; posed: the lines rest part way through a play
  let mode='normal',built=[],builtFor=0,viewsFor=null,lens=[],styles=[],samples=[],G=null,tipEls=[],marker=null;
  let running=false,playing=false,posed=false,filled=false,run=null,raf=0;

  function speed(){return slowTog.checked?dur*3:dur}
  // Drops a timer's id once it fires, so `timers` only ever holds ones still pending (not every id ever
  // scheduled) — Loop can run for a long time without the array growing without bound.
  function later(fn,wait){
    const id=setTimeout(()=>{
      const i=timers.indexOf(id);
      if(i>-1)timers.splice(i,1);
      fn();
    },wait);
    timers.push(id);
  }
  // Rebuilds the paths of the chosen drawing, and names it for screen readers.
  function buildPaths(){
    const drawing=DRAWINGS[current];
    svg.setAttribute('aria-label',drawing.label+(MORE[mode]||''));
    group.replaceChildren();
    builtFor=current;
    built=drawing.paths.map(d=>{
      const path=document.createElementNS('http://www.w3.org/2000/svg','path');
      path.setAttribute('d',d);
      path.setAttribute('class','draw-path');
      group.appendChild(path);
      return path;
    });
    if(mode!=='normal')rebuildViews();
    return built;
  }
  // One play rebuilds the paths hidden and draws them one after another, each starting a little after the
  // one before. While Loop is on, the finished drawing (filled, if Fills is on) holds 1200ms; whether it then vanishes and draws
  // again is decided right after that hold, from Loop's value at that moment, so switching Loop off during the hold leaves the
  // drawing shown. Slow motion stretches the draws, the fill's fade and the waits for them, not the hold. Under reduced motion the
  // lines are already complete (a CSS rule), so the fill comes at once instead of after the time the lines would have taken.
  function cycle(){
    const fillMs=slowTog.checked?1200:400;
    vars.setProperty('--fill-dur',fillMs+'ms');
    const paths=buildPaths(),ms=speed(),gap=ms*0.3,rev=revTog.checked;
    paths.forEach(path=>{
      const len=path.getTotalLength();
      path.style.strokeDasharray=len;
      path.style.strokeDashoffset=rev?-len:len;
      path.style.transition='none';
    });
    startRun();
    paths.forEach((path,i)=>later(()=>{
      path.getBoundingClientRect(); // apply the hidden state first, so the slide has a start value
      path.style.transition=`stroke-dashoffset ${ms}ms ${ease}`;
      path.style.strokeDashoffset=0;
    },20+i*gap));
    later(()=>{
      if(fillTog.checked)paths.forEach(path=>{path.style.transition='';path.classList.add('fill-done')});
      endRun(fillTog.checked);
      if(!motionOk)return settle();
      // a play that is not looping rests posed (in a mode) once the finished drawing has been held as long as a loop holds it
      later(()=>{if(loopTog.checked)cycle();else settle()},1200+(fillTog.checked?fillMs:0));
    },motionOk?20+(paths.length-1)*gap+ms+50:0);
  }
  function play(){timers.forEach(clearTimeout);timers=[];cycle()}

  document.getElementById('btn-play').addEventListener('click',play);
  loopTog.addEventListener('change',()=>{if(loopTog.checked)play()});
  function choices(id,pick){
    const buttons=document.querySelectorAll('#'+id+' button');
    buttons.forEach(b=>b.addEventListener('click',()=>{
      buttons.forEach(x=>{x.classList.toggle('on',x===b);x.setAttribute('aria-pressed',String(x===b))});
      pick(b.dataset);
      refresh();
    }));
  }
  function el(tag,attrs,parent){
    const e=document.createElementNS(NS,tag);
    for(const k in attrs)e.setAttribute(k,attrs[k]);
    parent.appendChild(e);return e;
  }
  function put(node,text){if(node.textContent!==text)node.textContent=text}
  // The value of a speed curve at a share x of its time: the curve's own t for x found by halving, then its height there
  function curveAt([a,b,c,e],x){
    const at=(p,q,t)=>3*p*t*(1-t)*(1-t)+3*q*t*t*(1-t)+t*t*t;
    let lo=0,hi=1,t=x;
    for(let i=0;i<30;i++){t=(lo+hi)/2;if(at(a,c,t)<x)lo=t;else hi=t}
    return at(b,e,t);
  }
  // The moment a resting view shows: one second into a play, or half-way through a play that is shorter than two seconds, so that no
  // line is finished (Fast, or one line). It goes by the play's own steps and Feel, not by Slow motion.
  function poseMs(){return Math.min(1000,Math.round((20+(built.length-1)*dur*.3+dur)/200)*100)}
  function pose(){
    const T=poseMs(),gap=dur*.3,curve=CURVES[ease],rev=revTog.checked;
    built.forEach((path,i)=>{
      const o=lens[i]*(1-curveAt(curve,Math.min(Math.max((T-20-i*gap)/dur,0),1)));
      path.style.setProperty('--po',(rev?-o:o)+'px');
      path.classList.add('pose');path.classList.remove('fill-done');
    });
    posed=true;stage.classList.add('posed');
  }
  // Back to Normal: the lines go to where the play left them (finished, filled if it filled), at once
  function unpose(){
    built.forEach(path=>{
      if(!path.classList.contains('pose'))return;
      path.style.transition='none';path.classList.remove('pose');
      path.classList.toggle('fill-done',filled);
    });
    posed=false;stage.classList.remove('posed');
  }
  // The faint routes (in the drawing), Compare's finished copy and the points that dots are placed from; made again after each play's rebuild
  function rebuildViews(){
    viewsFor=built;
    lens=built.map(path=>path.getTotalLength());
    styles=built.map(path=>getComputedStyle(path));
    routes.replaceChildren();copyG.replaceChildren();
    samples=built.map((path,i)=>{
      const pts=[],k=Math.ceil(lens[i]/6);
      for(let j=0;j<=k;j++){const q=path.getPointAtLength(lens[i]*j/k);pts.push(q.x,q.y)}
      return pts;
    });
    built.forEach((path,i)=>{
      const d=path.getAttribute('d');
      el('path',{d},routes);
      const copy=el('path',{d,class:'draw-path'},copyG);
      copy.style.strokeDasharray=lens[i];copy.style.strokeDashoffset=0;
    });
    syncCopy();
  }
  function syncCopy(){for(const c of copyG.children)c.classList.toggle('fill-done',fillTog.checked)}
  // A line's number dot: close to its start, behind it or beside it (never ahead, where the pen tip passes). A spot counts as free when it
  // touches no line and no other dot and stays inside the drawing's box; of the free ones the nearest to the start wins. Where none is
  // free (a small logo on a phone) the least bad one is used, and the drawing gives it a thin leader to the start.
  function dotAt(i,taken){
    const s=G.s,R=G.r,rev=revTog.checked,len=lens[i],half=s*(+vars.getPropertyValue('--stroke-w')||2)/2;
    const P=built[i].getPointAtLength(rev?len:0),Q=built[i].getPointAtLength(rev?len-4:4);
    const m=Math.hypot(P.x-Q.x,P.y-Q.y)||1,bx=(P.x-Q.x)/m,by=(P.y-Q.y)/m,sx=G.ox+s*P.x,sy=G.oy+s*P.y;
    let best=null;
    for(const d of [R+6,R+14,R+24])for(const deg of [0,45,-45,90,-90,135,-135,180]){
      const a=deg*Math.PI/180,cx=sx+(bx*Math.cos(a)-by*Math.sin(a))*d,cy=sy+(bx*Math.sin(a)+by*Math.cos(a))*d;
      let clear=1e9,near=1e9;
      for(const pts of samples)for(let j=0;j<pts.length;j+=2)clear=Math.min(clear,Math.hypot(G.ox+s*pts[j]-cx,G.oy+s*pts[j+1]-cy));
      for(const t of taken)near=Math.min(near,Math.hypot(t.cx-cx,t.cy-cy));
      const out=Math.max(0,G.zl-(cx-R),G.zt-(cy-R),cx+R-G.zr,cy+R-G.zb);
      const miss=Math.max(0,R+4-(clear-half))+Math.max(0,2*R+5-near)+Math.max(0,out-SLACK);
      const score=miss*50+d+Math.abs(deg)*.05+out;
      if(!best||score<best.score)best={score,cx,cy,sx,sy,d};
    }
    taken.push(best);return best;
  }
  // See inside, drawn in the box's own pixels: the time line (a bar for each line, from the play's own steps and speed, and the fill),
  // the dots, the pen tips, and the room the drawing is left (the words above and the time line below take theirs from their sizes)
  function drawInside(){
    const W=stage.clientWidth,H=stage.clientHeight,n=built.length;
    if(!W||!n)return;
    const fill=fillTog.checked,ms=speed(),gap=ms*.3,fms=slowTog.checked?1200:400,fillAt=(n-1)*gap+ms+30,total=fillAt+(fill?fms:0);
    const secs=Math.round(total/500)/2;
    put(capB,n>1?'1, 2, 3: the order they draw in':'1: where the line starts');
    put(capPh,' · '+capB.textContent);
    put(capC,(n>1?'Each starts a little after the one before: ':'The line draws from its dot: ')+'about '+
      (secs<1?'half a second':secs===1?'a second':(secs%1?Math.floor(secs)+'½':secs)+' seconds')+' in all');
    const rows=n+(fill?1:0),axisY=H-PAD-capC.offsetHeight-13,top=axisY-4-(rows*PITCH-(PITCH-ROW));
    stage.style.setProperty('--io-t',PAD+Math.max(capA.offsetHeight,capB.offsetHeight)+GAP+'px');
    stage.style.setProperty('--io-b',H-top+GAP+'px');
    const r=svg.getBoundingClientRect(),b=stage.getBoundingClientRect(),s=Math.min(r.width/400,r.height/260);
    const zl=r.left-b.left-stage.clientLeft,zt=r.top-b.top-stage.clientTop;
    G={s,r:Math.round(Math.max(8,Math.min(DOT_R,s*17))),ox:zl+(r.width-400*s)/2,oy:zt+(r.height-260*s)/2,zl,zt,zr:zl+r.width,zb:zt+r.height,total,x0:PAD+18,x1:W-PAD};
    const X=t=>G.x0+(G.x1-G.x0)*t/total;
    over.replaceChildren();
    for(let i=0;i<rows;i++){
      const last=fill&&i===n,t0=last?fillAt:i*gap,t1=t0+(last?fms:ms),y=top+i*PITCH;
      el('rect',{class:last?'bar fillbar':'bar',x:X(t0),y,width:X(t1)-X(t0),height:ROW,rx:ROW/2},over);
      if(!last)el('text',{x:PAD+6,y:y+ROW/2},over).textContent=i+1;
    }
    let ticks=`M${G.x0} ${axisY}H${G.x1}`;
    for(let k=1;k*1000<=total;k++)ticks+=`M${X(k*1000)} ${axisY}v5`;
    el('path',{class:'axis',d:ticks},over);
    marker=el('rect',{class:'mk',x:-1,y:top-2,width:2,height:axisY+7-top},over);
    capFill.style.display=fill?'':'none';
    if(fill){
      capFill.style.left=Math.max(G.x0,X(fillAt)-capFill.offsetWidth-6)+'px';
      capFill.style.top=top+n*PITCH+ROW/2-capFill.offsetHeight/2+'px';
    }
    const taken=[];
    built.forEach((path,i)=>{
      const c=dotAt(i,taken);
      if(c.d>G.r+10)el('path',{class:'lead',d:`M${c.sx} ${c.sy}L${c.cx} ${c.cy}`},over);
      const g=el('g',{},over);
      g.style.transform=`translate(${c.cx}px,${c.cy}px)`;
      el('circle',{class:'dot',r:G.r},g);el('text',{},g).textContent=i+1;
    });
    tipEls=built.map(()=>el('circle',{class:'tip',r:TIP_R},over));
    drawLive();
  }
  // What moves: the marker along the time line (from the first line's own transition, so it keeps step; at rest, where the pose is) and each
  // pen tip at the edge of its line's drawn part, read from the line's dash as it is now
  function drawLive(){
    if(mode!=='inside'||!G||!marker)return;
    let t=G.total;
    if(posed)t=(poseMs()-20)*speed()/dur;
    else if(playing){
      const a=run.start===null&&built[0].getAnimations()[0];
      if(a&&a.startTime!==null)run.start=a.startTime;
      t=document.timeline.currentTime-(run.start===null?run.t0:run.start);
    }
    marker.style.transform=`translateX(${G.x0+(G.x1-G.x0)*Math.min(Math.max(t,0),G.total)/G.total}px)`;
    tipEls.forEach((tip,i)=>{
      const o=parseFloat(styles[i].strokeDashoffset),len=lens[i],on=Math.abs(o)>.5&&Math.abs(o)<len-.5;
      tip.style.opacity=on?1:0;
      const pt=built[i].getPointAtLength(o>0?len-o:-o);
      tip.style.transform=`translate(${G.ox+G.s*pt.x}px,${G.oy+G.s*pt.y}px)`;
    });
  }
  function frame(){raf=0;drawLive();kick()}
  function kick(){if(!raf&&mode==='inside'&&playing&&motionOk)raf=requestAnimationFrame(frame)}
  // A play begins: the pose is lifted (the lines were just rebuilt, hidden), and See inside's pen tips and marker follow it
  function startRun(){
    running=playing=true;filled=false;posed=false;stage.classList.remove('posed');
    run={start:null,t0:performance.now()+20};
    if(mode==='inside')drawInside();
    kick();
  }
  function endRun(fillOn){filled=fillOn;playing=false;drawLive()}
  // Nothing is pending: in a mode the lines rest posed
  function settle(){running=false;refresh()}
  // Redraws the mode for what is set now (a mode press, a setting, a resize, a font arriving, the end of a play)
  function refresh(){
    if(mode==='normal'||!built.length)return;
    if(!running){
      if(builtFor!==current){
        buildPaths().forEach(path=>{path.style.strokeDasharray=path.getTotalLength();path.style.strokeDashoffset=0});
        filled=false;
      }
      pose();
    }
    put(capPose,poseMs()<1000?'Under a second in':'One second in');
    syncCopy();
    if(!motionOk){
      const when=poseMs()<1000?'under a second':'one second';
      put(notes.inside,`Shown still, ${when} in: each line is all there, hidden by a dash as long as the line; the drawn part starts at the dot, in the numbered order.`);
      put(notes.compare,`Shown still, ${when} in: Already there is finished at once; Draws itself is only part way, with the rest of each line still hidden.`);
    }
    if(mode==='inside')drawInside();
  }
  // The mode switch: draws the mode at once. The shared script then presses Replay (not under reduced motion), which plays it.
  document.addEventListener('hb:mode',e=>{
    mode=e.detail.mode;
    svg.setAttribute('aria-label',DRAWINGS[builtFor].label+(MORE[mode]||''));
    if(mode==='normal')return unpose();
    if(viewsFor!==built)rebuildViews();
    refresh();kick();
  });
  new ResizeObserver(refresh).observe(stage);
  document.fonts.ready.then(refresh);
  [revTog,fillTog,slowTog].forEach(t=>t.addEventListener('change',refresh));
  choices('drawing-seg',d=>{current=+d.drawing});
  choices('speed-seg',d=>{dur=+d.ms});
  choices('width-seg',d=>{vars.setProperty('--stroke-w',d.w)});
  choices('feel-seg',d=>{ease=d.ease});
  choices('color-sw',d=>{vars.setProperty('--stroke-color',d.color)});
</script>
</body>
</html>