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.

33.5 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>Floating Elements — Animation Handbook</title>
  <meta name="description" content="Small shapes drift slowly, each on its own path. Best for hero backgrounds.">
  <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/floating-elements/">
  <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="Floating Elements — Animation Handbook">
  <meta property="og:description" content="Small shapes drift slowly, each on its own path. Best for hero backgrounds.">
  <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/floating-elements/">
  <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="Floating Elements — Animation Handbook">
  <meta name="twitter:description" content="Small shapes drift slowly, each on its own path. Best for hero backgrounds.">
  <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": "Floating Elements", "name": "Floating Elements", "description": "Small shapes drift slowly, each on its own path. Best for hero backgrounds.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/floating-elements/", "inLanguage": "en", "articleSection": "Ambient & Background", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, Ambient & Background, Floating Elements"}</script>
  <style>
    :root{--ui-accent:#ffce5a}
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    .stage{position:relative;overflow:hidden;background:#03050a}
    .float-layer{position:absolute;inset:0;overflow:hidden}
    .el{position:absolute;will-change:transform;opacity:.5}
    .fg-card{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:clamp(200px,60%,320px);background:rgba(3,5,10,.8);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border:1px solid rgba(255,255,255,.1);border-radius:10px;padding:24px;z-index:10;text-align:center}
    .fg-eyebrow{font-size:11px;font-weight:600;letter-spacing:2px;text-transform:uppercase;color:var(--ui-accent);margin-bottom:10px}
    .fg-title{font-size:clamp(16px,2.2vw,22px);font-weight:700;color:#fff;margin-bottom:10px;line-height:1.2}
    .fg-body{font-size:13px;color:rgba(255,255,255,.72);line-height:1.6}
    /* On phones and short screens the card shrinks to leave the shapes in view */
    @media(max-width:600px),(max-height:760px){.fg-card{padding:12px 14px}.fg-eyebrow{margin-bottom:4px}.fg-title{margin-bottom:0}.fg-body{display:none}}
    /* See inside and Compare: a canvas for the marks, a second set of shapes for the first half, a divider, and plain words on dark pills */
    .guide,.copy-layer,.divide,.lbl{display:none}
    .guide{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:4}
    .divide{position:absolute;top:0;bottom:0;left:50%;width:2px;margin-left:-1px;background:#2a2e3a;z-index:3}
    .lbl{position:absolute;left:0;top:0;z-index:20;padding:4px 9px;border-radius:999px;background:rgba(3,5,10,.92);color:#f4f4f2;font:600 13px/1.2 var(--hb-font);white-space:nowrap;pointer-events:none}
    .fl{width:max-content;max-width:calc(100% - 16px);white-space:normal}
    .side{top:10px}.side.first{left:10px}.side.second{left:calc(50% + 10px)}
    .k-cross::before{content:"+";color:var(--ui-accent);font-weight:700;margin-right:6px}
    .k-oval::before,.k-push::before{content:"";display:inline-block;border:1px dashed #cfd2d8;margin-right:6px;vertical-align:-1px}
    .k-oval::before{width:14px;height:9px;border-radius:50%}
    .k-push::before{width:11px;height:11px;border-radius:50%}
    .stage[data-hb-mode="inside"] .guide,.stage[data-hb-mode="compare"] .guide,.stage[data-hb-mode="compare"] .divide,.stage[data-hb-mode="compare"] .side,.stage[data-hb-mode="inside"] .fl:not([hidden]){display:block}
    .stage[data-hb-mode="inside"] .fg-card,.stage[data-hb-mode="compare"] .fg-card{display:none}
    .stage[data-hb-mode="compare"] .float-layer{top:40px;left:50%}
    .stage[data-hb-mode="compare"] .copy-layer{display:block;left:0;right:50%}
    .stage[data-hb-mode="compare"] .el.skip{display:none}
    @media(max-width:360px){.lbl{font-size:12px;line-height:15px;padding:3px 7px}.side.first{left:6px}.side.second{left:calc(50% + 6px)}}
  </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="loop">
<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="../ambient-ripple/" rel="prev" aria-label="Previous: Ambient Ripple Effect"><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>Ambient Ripple Effect</span></a><a href="../grid-dot-pattern-parallax/" rel="next" aria-label="Next: Grid / Dot Pattern Parallax"><span><span class="hb-dir">Next: </span>Grid / Dot Pattern Parallax</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">07.10 · Ambient &amp; Background</p>
    <h1>Floating Elements</h1>
    <p class="hb-lede">Small shapes drift slowly, each on its own path. Best for hero backgrounds.</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 moves by itself. Pause it to look closely, or 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">
      <div class="float-layer" id="float-layer" aria-hidden="true"></div>
      <div class="float-layer copy-layer" id="copy-layer" aria-hidden="true" inert></div>
      <div class="fg-card">
        <div class="fg-eyebrow">Floating elements</div>
        <div class="fg-title">No two shapes move together</div>
        <div class="fg-body">Each shape follows its own slow path, so the motion never looks mechanical.</div>
      </div>
      <div class="divide" aria-hidden="true"></div>
      <canvas class="guide" id="guide" aria-hidden="true"></canvas>
      <p class="lbl fl k-cross" aria-hidden="true" data-hb-caption>Cross: each shape's home spot</p>
      <p class="lbl fl k-oval" aria-hidden="true" data-hb-caption>It wanders inside its own oval</p>
      <p class="lbl fl" aria-hidden="true" data-hb-caption>Each at its own pace: one to two and a half minutes across and back</p>
      <p class="lbl fl k-push" aria-hidden="true" data-hb-caption hidden>Shapes slide away from your pointer or finger</p>
      <p class="lbl side first" aria-hidden="true" data-hb-caption>All in step</p>
      <p class="lbl side second" aria-hidden="true" data-hb-caption>Own paths</p>
    </div>
    <div class="hb-player">
      <button class="hb-play" type="button" id="btn-pause" data-hb-pause data-state="playing"><svg class="hb-ic hb-i-pause" viewBox="0 0 24 24" aria-hidden="true"><rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/></svg><svg class="hb-ic hb-i-play" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 3l14 9-14 9z"/></svg><span class="hb-pause-label">Pause</span></button>
      <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 shape has its own home spot and wanders inside its own dashed oval, at its own pace, so no two ever move together.</p>
      <p data-hb-for="compare" hidden>All in step moves every shape along the same path at the same time, like one sheet. Own paths gives every shape its own way and pace, so it looks alive.</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 see the difference as it moves.</p></div>
    </div>
    <div class="hb-settings">
      <div class="hb-setting">
        <p class="hb-setting-name" id="count-lbl">Number of shapes</p>
        <div class="seg" id="count-seg" role="group" aria-labelledby="count-lbl">
          <button type="button" data-n="5" aria-pressed="false">Few</button>
          <button type="button" data-n="8" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-n="14" aria-pressed="false">Many</button>
        </div>
        <p class="hb-hint">5 to 12 shapes feels calm; more gets busy.</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-spd="0.3" aria-pressed="false">Slow</button>
          <button type="button" data-spd="0.5" class="on" aria-pressed="true">Normal</button>
          <button type="button" data-spd="0.8" aria-pressed="false">Fast</button>
        </div>
        <p class="hb-hint">How fast the shapes drift.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="range-lbl">How far they drift</p>
        <div class="seg" id="range-seg" role="group" aria-labelledby="range-lbl">
          <button type="button" data-px="30" aria-pressed="false">Short</button>
          <button type="button" data-px="50" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-px="90" aria-pressed="false">Long</button>
        </div>
        <p class="hb-hint">How far each shape wanders from its place.</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="shape-lbl">Shapes</p>
          <div class="seg" id="shape-seg" role="group" aria-labelledby="shape-lbl">
            <button type="button" data-shape="circles" aria-pressed="false">Circles</button>
            <button type="button" data-shape="squares" aria-pressed="false">Squares</button>
            <button type="button" data-shape="rings" aria-pressed="false">Rings</button>
            <button type="button" data-shape="mixed" class="on" aria-pressed="true">Mixed</button>
          </div>
          <p class="hb-hint">The kind of shapes that float.</p>
        </div>
        <div class="hb-setting">
          <p class="hb-setting-name" id="pal-lbl">Colors</p>
          <div class="seg" id="pal-seg" role="group" aria-labelledby="pal-lbl">
            <button type="button" data-pal="cool" class="on" aria-pressed="true">Cool</button>
            <button type="button" data-pal="warm" aria-pressed="false">Warm</button>
            <button type="button" data-pal="mono" aria-pressed="false">Gray</button>
            <button type="button" data-pal="neon" aria-pressed="false">Neon</button>
          </div>
          <p class="hb-hint">The set of colors the shapes use.</p>
        </div>
        <div class="hb-setting">
          <label class="hb-switch-row"><span>Shapes turn</span><input class="hb-switch" type="checkbox" role="switch" id="rot-tog" checked autocomplete="off"></label>
          <p class="hb-hint">Each shape slowly spins as it drifts.</p>
        </div>
        <div class="hb-setting">
          <label class="hb-switch-row"><span>Fades in and out</span><input class="hb-switch" type="checkbox" role="switch" id="pulse-tog" checked autocomplete="off"></label>
          <p class="hb-hint">Each shape slowly brightens and dims.</p>
        </div>
        <div class="hb-setting">
          <label class="hb-switch-row"><span>Shapes avoid the pointer</span><input class="hb-switch" type="checkbox" role="switch" id="react-tog" autocomplete="off"></label>
          <p class="hb-hint">Shapes near your pointer or finger slide aside.</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 floating shapes to [the section you want a gentle moving background behind]. Scatter a handful of small, see-through circles, squares or rings, and move each one slowly around its own starting point on a smooth, looping path, giving every shape its own speed, distance and starting point so no two ever move in step. Keep them behind the content and let clicks pass through. When the settings include it, shapes slide away from the pointer, or from a finger on touch screens. If the visitor has reduced motion turned on, keep the shapes still. 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>Hero backgrounds</li><li>Landing pages</li><li>Onboarding screens</li><li>Empty states</li></ul>
      <h3>Avoid on</h3>
      <ul class="hb-tags hb-avoid"><li>Busy layouts</li><li>Long reading pages</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 layer=document.getElementById('float-layer');
  const stage=document.querySelector('.stage');
  const slowTog=document.getElementById('slow-tog');
  const FRAME=1000/60; // one step is what a 60 Hz frame adds, so a faster screen or a slow frame does not change the speed
  let W=0,H=0,raf=null,lastT=null,paused=false,t=0,mouse={x:-999,y:-999};
  let COUNT=8,SPD=0.5,RANGE=50,SHAPE='mixed',PAL='cool',ROT=true,PULSE=true,REACT=false;
  let elements=[];

  // See inside and Compare: a canvas over the shapes for the marks, a second set of shapes for Compare's first half, the captions
  // and the notes. NM is the room the half names take above each half, NP the steps of a path line, TAIL the time a path line
  // covers for each unit of Speed.
  const copyLayer=document.getElementById('copy-layer'),guide=document.getElementById('guide'),gx=guide.getContext('2d');
  const caps=[...document.querySelectorAll('.fl')],paceCap=caps[2],pushCap=caps[3];
  const noteIn=document.querySelector('[data-hb-for="inside"]'),noteCmp=document.querySelector('[data-hb-for="compare"]');
  const phone=matchMedia('(max-width:600px),(max-height:500px)');
  const ACCENT=getComputedStyle(document.documentElement).getPropertyValue('--ui-accent').trim();
  const NM=40,NP=16,TAIL=6,TAU=Math.PI*2,DASH=[4,5],SOLID=[];
  const FADE=['rgba(244,244,242,.12)','rgba(244,244,242,.25)','rgba(244,244,242,.42)','rgba(244,244,242,.7)']; // a path line, faintest part first
  const SH={amp:0,freq:.55,phase:1.5,phaseY:1.4,rotSpd:.1,pulsePhs:0}; // what every shape in the first half shares: the middle of each range
  const SP={x:0,y:0},PT={x:-999,y:-999,over:-1};
  let mode='normal',copies=[],copiesOf=null,srot=0,DPR=1,IB=0; // IB: the room See inside's captions take along the top on a phone
  // The notes hold their moving words in the markup; the still ones show while the loop is paused
  const GO_IN=noteIn.textContent,GO_CMP=noteCmp.textContent;
  const STILL_IN='Inside, shown still: each shape has its own home spot and wanders inside its own dashed oval, at its own pace.';
  const STILL_CMP='Shown still: the line behind each shape is its recent path, the same for all in All in step and different for each in Own paths.';

  const PALETTES={
    cool:['rgba(88,166,255,.3)','rgba(100,80,220,.3)','rgba(56,200,180,.25)'],
    warm:['rgba(255,166,87,.3)','rgba(248,81,73,.3)','rgba(255,210,100,.25)'],
    mono:['rgba(200,210,220,.15)','rgba(150,160,170,.12)','rgba(240,245,255,.1)'],
    neon:['rgba(0,255,180,.4)','rgba(255,0,200,.35)','rgba(0,200,255,.4)']
  };

  const SHAPES=['circle','square','ring'];
  // Swap the alpha channel of an rgba() string, e.g. rgba(88,166,255,.3) -> rgba(88,166,255,0.6)
  const withAlpha=(c,a)=>c.replace(/[\d.]+\)$/,a+')');

  function mkEl(){
    const shapePick=SHAPE==='mixed'?SHAPES[Math.floor(Math.random()*SHAPES.length)]:SHAPE.replace(/s$/,'');
    const sz=8+Math.random()*20;
    const col=PALETTES[PAL][Math.floor(Math.random()*PALETTES[PAL].length)];
    const el=document.createElement('div');el.className='el';
    const bx=10+Math.random()*80,by=10+Math.random()*80;
    const amp=RANGE*.5+Math.random()*RANGE*.5;
    const freq=0.3+Math.random()*0.5;
    const phase=Math.random()*Math.PI*2;
    const phaseY=Math.random()*Math.PI*2;
    const rotSpd=(Math.random()-.5)*0.3;
    const pulsePhs=Math.random()*Math.PI*2;

    el.style.width=sz+'px';el.style.height=sz+'px';
    if(shapePick==='ring'){
      el.style.borderRadius='50%';el.style.border='2px solid '+withAlpha(col,0.6);
      el.style.background='none';
    }else if(shapePick==='square'){
      el.style.background=col;
    }else{
      el.style.borderRadius='50%';el.style.background=col;
    }
    layer.appendChild(el);
    return{el,sz,bx,by,amp,freq,phase,phaseY,rotSpd,pulsePhs,rot:0,px:0,py:0,hx:0,hy:0,off:false};
  }

  // Where a shape sits at time tt in a box pw wide and ph tall: its home plus the two sways, then slid aside by the pointer when
  // Shapes avoid the pointer is on. m holds its pace, drift and phases: its own, or the ones the first half shares. Writes SP.
  function spot(bx,by,m,tt,pw,ph){
    let x=bx/100*pw+Math.sin(m.freq*tt+m.phase)*m.amp;
    let y=by/100*ph+Math.cos(m.freq*tt*0.7+m.phaseY)*m.amp*.6;
    // Shapes avoid the pointer
    if(REACT&&PT.x>0){
      const dx=x-PT.x,dy=y-PT.y,d=Math.sqrt(dx*dx+dy*dy);
      if(d>0&&d<120){const f=120-d;x+=dx/d*f*.08;y+=dy/d*f*.08;}
    }
    SP.x=x;SP.y=y;
  }
  // In Compare the pointer counts from the corner of the half it is over, so it acts at the same spot of both halves
  function aimLocal(){
    const cmp=mode==='compare';
    PT.over=cmp&&mouse.x>0?(mouse.x>=W/2?1:0):-1;
    PT.x=PT.over===1?mouse.x-W/2:mouse.x;
    PT.y=mouse.y-(cmp?NM:IB);
  }

  // Writes each shape's position, turn and opacity for t: every frame, after rebuild(), and after a setting changes while paused.
  // In Compare the real shapes fill the right half and their copies, moving by the shared numbers, the left one.
  function place(){
    aimLocal();
    const cmp=mode==='compare',pw=cmp?W/2:W,ph=cmp?H-NM:H-IB;
    for(const e of elements){
      spot(e.bx,e.by,e,t,pw,ph);
      e.px=SP.x;e.py=SP.y;e.hx=e.bx/100*pw+e.sz/2;e.hy=e.by/100*ph+e.sz/2;
      const op=PULSE?0.4+0.3*Math.sin(e.pulsePhs+t*.5):0.5;
      e.el.style.transform=`translate(${SP.x.toFixed(1)}px,${SP.y.toFixed(1)}px) rotate(${(ROT?e.rot:0).toFixed(1)}deg)`;
      e.el.style.opacity=op;
    }
    if(!cmp)return;
    SH.amp=RANGE*.75;
    const op=PULSE?0.4+0.3*Math.sin(t*.5):0.5;
    for(let i=0;i<copies.length;i++){
      spot(elements[i].bx,elements[i].by,SH,t,pw,ph);
      copies[i].style.transform=`translate(${SP.x.toFixed(1)}px,${SP.y.toFixed(1)}px) rotate(${(ROT?srot:0).toFixed(1)}deg)`;
      copies[i].style.opacity=op;
    }
  }

  function rebuild(){
    layer.textContent='';
    elements=Array.from({length:COUNT},mkEl);
    if(mode==='compare')copies=buildCopies();
    place();
    if(mode!=='normal'){layout();draw();}
  }
  // One inert, hidden copy of each shape, made again whenever the shapes are
  function buildCopies(){
    copyLayer.textContent='';copiesOf=elements;
    return elements.map(e=>{
      const c=e.el.cloneNode(false);c.setAttribute('aria-hidden','true');c.inert=true;
      copyLayer.appendChild(c);return c;
    });
  }

  // One pending frame at a time: Pause cancels it, Play starts one loop again. A step moves t and each turn (a third of a step in
  // slow motion). A frame adds as many steps as 60ths of a second have passed since the last one, so the shapes drift at the same
  // speed on every screen. A long gap (a background tab) counts for at most 50 ms, and the first frame after a start adds none.
  function loop(ts){
    raf=requestAnimationFrame(loop);
    const dt=lastT===null?0:Math.min(ts-lastT,50);
    lastT=ts;
    const k=dt/FRAME*(slowTog.checked?1/3:1);
    t+=SPD*.005*k;
    if(ROT)elements.forEach(e=>{e.rot+=e.rotSpd*k});
    if(ROT&&mode==='compare')srot+=SH.rotSpd*k;
    place();draw();
  }
  function start(){if(raf)return;lastT=null;raf=requestAnimationFrame(loop)}

  // Top level, so it is there before the shared script (deferred) pauses the loop on arrival under reduced motion. Paused shapes stay put.
  document.addEventListener('hb:pause',e=>{
    paused=e.detail.paused;
    if(paused){cancelAnimationFrame(raf);raf=null}
    else start();
    notes();
  });
  // The mode switch draws the mode at once, paused or not. The real shapes and their time carry on unchanged for Normal.
  document.addEventListener('hb:mode',e=>{
    mode=e.detail.mode;
    if(mode==='compare'&&copiesOf!==elements)copies=buildCopies();
    layout();draw();notes();
  });
  // A tab that comes back after being hidden has no earlier frame to measure from, so its first frame adds no step
  document.addEventListener('visibilitychange',()=>{lastT=null});

  // A real change of the stage's size places the shapes again, playing or paused; the same size (a phone's address bar) does nothing
  function resize(){
    const w=stage.clientWidth,h=stage.clientHeight;
    if(w===W&&h===H)return;
    W=w;H=h;DPR=Math.min(window.devicePixelRatio||1,2);
    guide.width=Math.round(W*DPR);guide.height=Math.round(H*DPR);
    place();
    if(mode!=='normal'){layout();draw();}
  }

  // The pointer's position comes from pointermove and pointerdown, so a finger resting on the stage counts too
  function aim(e){const r=stage.getBoundingClientRect();mouse.x=e.clientX-r.left;mouse.y=e.clientY-r.top}
  stage.addEventListener('pointermove',aim);
  stage.addEventListener('pointerdown',aim);
  stage.addEventListener('pointerleave',()=>{mouse.x=-999});
  stage.addEventListener('pointercancel',()=>{mouse.x=-999});

  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);
    }));
  }
  // While paused, a setting that changes how the shapes look places them again so the change shows
  function still(){if(paused){place();draw()}}
  // The settings that build the shapes ignore a press on the choice already made, so it does not scatter a new arrangement
  choices('count-seg',d=>{if(+d.n===COUNT)return;COUNT=+d.n;rebuild()});
  choices('speed-seg',d=>{SPD=+d.spd;pace();still()});
  choices('range-seg',d=>{if(+d.px===RANGE)return;RANGE=+d.px;rebuild()});
  choices('shape-seg',d=>{if(d.shape===SHAPE)return;SHAPE=d.shape;rebuild()});
  choices('pal-seg',d=>{if(d.pal===PAL)return;PAL=d.pal;rebuild()});
  document.getElementById('rot-tog').addEventListener('change',e=>{ROT=e.target.checked;still()});
  document.getElementById('pulse-tog').addEventListener('change',e=>{PULSE=e.target.checked;still()});
  document.getElementById('react-tog').addEventListener('change',e=>{
    REACT=e.target.checked;pushCap.hidden=!REACT;still();
    relay();
  });

  // Which shapes a half shows (every other one on a phone in Compare, so a half keeps Normal's crowd), the room the captions
  // take, the shapes in the room that is left, then the captions
  function layout(){
    const thin=mode==='compare'&&phone.matches;
    elements.forEach((e,i)=>{
      e.off=thin&&i%2===1;e.el.classList.toggle('skip',e.off);
      if(copies[i])copies[i].classList.toggle('skip',e.off);
    });
    band();place();placeCaps();
  }
  function relay(){if(mode==='inside'){layout();draw()}}
  // On a phone or in a small box there is no spot the shapes never pass, so See inside's captions are packed into rows along the top,
  // at the wrap that takes the least height, and the shapes, homes and marks live in the room under them
  function band(){
    let h=0;
    if(mode==='inside'&&(phone.matches||W*H<190000)){
      const on=caps.filter(c=>!c.hidden);let best=null;
      for(const mw of [W-16,Math.min(300,W-16),Math.min(240,W-16)]){
        let x=8,y=8,row=0;const at=[];
        for(const c of on){
          c.style.maxWidth=mw+'px';c.style.left=c.style.top='0px';
          const w=c.offsetWidth,ch=c.offsetHeight;
          if(x>8&&x+w>W-8){x=8;y+=row+4;row=0}
          at.push([x,y]);x+=w+6;row=Math.max(row,ch);
        }
        if(!best||y+row+8<best.h-2)best={h:y+row+8,mw,at};
      }
      on.forEach((c,i)=>{c.style.maxWidth=best.mw+'px';c.style.left=best.at[i][0]+'px';c.style.top=best.at[i][1]+'px'});
      h=best.h;
    }
    if(h!==IB){IB=h;layer.style.top=h?h+'px':''}
  }
  // See inside's captions each take the free spot nearest their own corner, at the widest wrap that has one: clear of every cross
  // and the other captions and, if it can be, of the ovals the shapes wander in. Worked out when the picture, its size or the
  // words change, not every frame.
  const hit=(a,b,c,d,x,y,w,h)=>a<x+w&&x<a+c&&b<y+h&&y<b+d;
  function placeCaps(){
    if(mode!=='inside'||IB)return;
    const done=[];
    caps.forEach((c,i)=>{
      if(c.hidden)return;
      let pick=null,best=Infinity,seen=0;
      for(const mw of [W-16,260,200,150]){
        c.style.maxWidth=mw+'px';c.style.left=c.style.top='0px';
        const w=c.offsetWidth,h=c.offsetHeight,fx=i%2?W-8-w:8,fy=i<2?8:H-8-h;
        if(w===seen)continue;seen=w;
        for(let y=8;y<=Math.max(8,H-8-h);y+=8)for(let x=8;x<=Math.max(8,W-8-w);x+=8){
          let s=Math.hypot(x-fx,y-fy)*.05+(h-24)*1.6; // a longer wrap costs
          for(const e of elements){
            if(hit(x,y,w,h,e.hx-12,e.hy-12,24,24))s+=1e6;
            else if(hit(x,y,w,h,e.hx-e.amp,e.hy-e.amp*.6,e.amp*2,e.amp*1.2))s+=60;
          }
          for(const d of done)if(hit(x-6,y-6,w+12,h+12,d[0],d[1],d[2],d[3]))s+=1e9;
          if(s<best){best=s;pick=[x,y,w,h,mw]}
        }
      }
      c.style.maxWidth=pick[4]+'px';c.style.left=pick[0]+'px';c.style.top=pick[1]+'px';done.push(pick);
    });
  }
  // The pace caption works out how long the quickest and slowest shapes take to go across and back from Speed (slow motion
  // included), in half minutes
  const HALVES=['','half a','one','one and a half','two','two and a half','three','three and a half','four','four and a half'];
  function pace(){
    const rate=SPD*.3*(slowTog.checked?1/3:1),a=Math.round(TAU/(.8*rate)/30),b=Math.round(TAU/(.3*rate)/30);
    const unit=n=>n<3?' minute':' minutes';
    const span=b>9?Math.max(1,Math.round(a/2))+' to '+Math.round(b/2)+' minutes'
      :a===b?'about '+HALVES[a]+unit(a):(a<2?'half a minute':HALVES[a])+' to '+HALVES[b]+unit(b);
    const s='Each at its own pace: '+span+' across and back';
    if(paceCap.textContent===s)return;
    paceCap.textContent=s;relay();
  }
  slowTog.addEventListener('change',()=>{pace();still()});
  function notes(){
    const a=paused?STILL_IN:GO_IN,b=paused?STILL_CMP:GO_CMP;
    if(noteIn.textContent!==a)noteIn.textContent=a;
    if(noteCmp.textContent!==b)noteCmp.textContent=b;
  }

  // The canvas over the shapes, cleared and drawn again each frame (and at once when paused) from the shapes' own numbers
  function draw(){
    if(mode==='normal')return;
    gx.setTransform(DPR,0,0,DPR,0,0);gx.clearRect(0,0,W,H);
    if(mode==='inside')inside();else compare();
  }
  // See inside: each shape's home (a cross), the oval it wanders in (twice its drift wide, 0.6 of that tall), a line from home to
  // the shape's middle (a dot), and while the pointer is over the box a ring as far as it pushes. All at the shape's middle.
  function inside(){
    gx.save();gx.beginPath();gx.rect(0,IB,W,H-IB);gx.clip();gx.translate(0,IB);
    gx.setLineDash(DASH);gx.strokeStyle='rgba(244,244,242,.4)';gx.lineWidth=1;gx.beginPath();
    for(const e of elements){gx.moveTo(e.hx+e.amp,e.hy);gx.ellipse(e.hx,e.hy,e.amp,e.amp*.6,0,0,TAU)}
    if(REACT&&PT.x>0){gx.moveTo(PT.x+120,PT.y);gx.arc(PT.x,PT.y,120,0,TAU)}
    gx.stroke();gx.setLineDash(SOLID);
    gx.strokeStyle='rgba(255,255,255,.65)';gx.beginPath();
    for(const e of elements){gx.moveTo(e.hx,e.hy);gx.lineTo(e.px+e.sz/2,e.py+e.sz/2)}
    gx.stroke();
    gx.fillStyle='#fff';gx.beginPath();
    for(const e of elements){gx.moveTo(e.px+e.sz/2+3,e.py+e.sz/2);gx.arc(e.px+e.sz/2,e.py+e.sz/2,3,0,TAU)}
    gx.fill();
    gx.strokeStyle=ACCENT;gx.lineWidth=1.5;gx.beginPath();
    for(const e of elements){gx.moveTo(e.hx-6,e.hy);gx.lineTo(e.hx+6,e.hy);gx.moveTo(e.hx,e.hy-6);gx.lineTo(e.hx,e.hy+6)}
    gx.stroke();gx.restore();
  }
  // Compare: in each half every shape trails a line that fades away behind it, its path over a stretch of time worked out from its
  // numbers (the first half's shared, the second's own); a dashed ring in the half the pointer is not over shows where it pushes.
  // A shape that has left its half takes its line with it.
  function compare(){
    const pw=W/2,ph=H-NM,span=TAIL*SPD,per=NP/4;
    for(let h=0;h<2;h++){
      gx.save();gx.beginPath();gx.rect(h*pw,NM,pw,ph);gx.clip();gx.translate(h*pw,NM);
      gx.lineWidth=1.5;gx.lineCap='round';
      for(let q=0;q<4;q++){
        gx.strokeStyle=FADE[q];gx.beginPath();
        for(const e of elements){
          spot(e.bx,e.by,h?e:SH,t,pw,ph);
          if(e.off||SP.x<-e.sz||SP.x>pw||SP.y<-e.sz||SP.y>ph)continue;
          for(let j=q*per;j<=(q+1)*per;j++){
            spot(e.bx,e.by,h?e:SH,t-span*(1-j/NP),pw,ph);
            if(j>q*per)gx.lineTo(SP.x+e.sz/2,SP.y+e.sz/2);else gx.moveTo(SP.x+e.sz/2,SP.y+e.sz/2);
          }
        }
        gx.stroke();
      }
      if(REACT&&PT.over>=0&&PT.over!==h){
        gx.setLineDash(DASH);gx.lineWidth=1;gx.strokeStyle='rgba(244,244,242,.4)';gx.beginPath();
        gx.arc(PT.x,PT.y,120,0,TAU);gx.stroke();gx.setLineDash(SOLID);
      }
      gx.restore();
    }
  }

  resize();
  rebuild();
  pace();
  window.addEventListener('resize',resize);
  phone.addEventListener('change',()=>{if(mode!=='normal'){layout();draw()}});
  if(document.fonts)document.fonts.ready.then(relay);
  start();
</script>
</body>
</html>