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.

30.2 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>Flocking — Animation Handbook</title>
  <meta name="description" content="Birds swirl and turn together as one flock. Best for calm backgrounds.">
  <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/flocking/">
  <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="Flocking — Animation Handbook">
  <meta property="og:description" content="Birds swirl and turn together as one flock. Best for calm backgrounds.">
  <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/flocking/">
  <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="Flocking — Animation Handbook">
  <meta name="twitter:description" content="Birds swirl and turn together as one flock. Best for calm 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": "Flocking", "name": "Flocking", "description": "Birds swirl and turn together as one flock. Best for calm backgrounds.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/flocking/", "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, Flocking"}</script>
  <style>
    :root{--ui-accent:#3fd6c4;--sky-top:#05070f;--sky-mid:#0c1230;--sky-low:#2a1a38;--bird:rgba(236,240,255,.92);--lead:#ffb454;--red:#ff6b6b;--blue:#5aa9ff;--green:#5be28a}
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    .stage{position:relative;overflow:hidden;background:linear-gradient(var(--sky-top),var(--sky-mid) 55%,var(--sky-low))}
    canvas{display:block;width:100%;height:100%}
    /* See inside and Compare: plain words over the canvas. The key sits in a corner and jumps to a free one when bird 0 comes near */
    .key,.half{display:none;position:absolute;pointer-events:none}
    .stage[data-hb-mode="inside"] .key{display:flex}
    .stage[data-hb-mode="compare"] .half{display:block}
    .lab{color:#f4f4f2;font:600 13px/1.25 var(--hb-font)}
    .key{left:10px;top:10px;flex-direction:column;gap:4px;max-width:min(260px,72%);padding:7px 10px;border-radius:8px;background:rgba(5,7,15,.9)}
    .key.right{left:auto;right:10px}.key.low{top:auto;bottom:10px}
    .key .lab{display:flex;align-items:center;gap:7px}
    .key .lab::before{content:"";flex:none;width:16px;height:3px;border-radius:2px;background:var(--c)}
    .key .ring::before{width:12px;height:12px;margin:0 2px;border:2px solid var(--c);border-radius:50%;background:none}
    .ring{--c:var(--lead)}.apart{--c:var(--red)}.same{--c:var(--blue)}.close{--c:var(--green)}
    .half{top:10px;padding:4px 10px;border-radius:999px;background:rgba(5,7,15,.9);white-space:nowrap}
    .half.first{left:10px}.half.second{left:calc(50% + 10px)}
    @media(max-width:600px){.lab{font-size:12px}}
  </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="../depth-map-photo/" rel="prev" aria-label="Previous: Depth-Map Photo"><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>Depth-Map Photo</span></a><a href="../ascii-halftone/" rel="next" aria-label="Next: ASCII / Halftone"><span><span class="hb-dir">Next: </span>ASCII / Halftone</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.21 · 3D &amp; Advanced</p>
    <h1>Flocking</h1>
    <p class="hb-lede">Birds swirl and turn together as one flock. Best for calm 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, and the birds swerve away from your pointer or finger. Pause it to look closely, or turn on slow motion.</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" id="stage">
      <canvas id="cvs" role="img" aria-label="Small light birds flying in flocks across a dark evening sky, swerving away from the pointer"></canvas>
      <div class="key" aria-hidden="true" inert>
        <p class="lab ring" data-hb-caption>Ring: the only birds it sees</p>
        <p class="lab apart" data-hb-caption>Keep apart</p>
        <p class="lab same" data-hb-caption>Fly the same way</p>
        <p class="lab close" data-hb-caption>Stay close (+ is their middle)</p>
      </div>
      <p class="lab half first" aria-hidden="true" inert data-hb-caption>On their own</p>
      <p class="lab half second" aria-hidden="true" inert data-hb-caption>As a flock</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>One bird (orange) sees only the birds in its ring (the rest fade) and follows three pulls: keep apart (red), fly the same way (blue) and stay close (green). Every bird does the same.</p>
      <p data-hb-for="compare" hidden>On their own: the same birds with no flock rules fly straight and scatter. As a flock: each follows its neighbors, so groups form and turn together.</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="size-lbl">Flock size</p>
        <div class="seg" id="size-seg" role="group" aria-labelledby="size-lbl">
          <button type="button" data-size="small" aria-pressed="false">Small</button>
          <button type="button" data-size="medium" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-size="large" aria-pressed="false">Large</button>
        </div>
        <p class="hb-hint">How many birds fly; phones show about half as many.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="close-lbl">How close they fly</p>
        <div class="seg" id="close-seg" role="group" aria-labelledby="close-lbl">
          <button type="button" data-close="loose" aria-pressed="false">Loose</button>
          <button type="button" data-close="normal" class="on" aria-pressed="true">Normal</button>
          <button type="button" data-close="tight" aria-pressed="false">Tight</button>
        </div>
        <p class="hb-hint">Tight flocks bunch up and turn together; loose ones spread out.</p>
      </div>
      <div class="hb-setting">
        <label class="hb-switch-row"><span>Flees the pointer</span><input class="hb-switch" type="checkbox" role="switch" id="flee-tog" checked autocomplete="off"></label>
        <p class="hb-hint">Birds swerve away from your pointer or finger.</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="speed-lbl">Speed</p>
          <div class="seg" id="speed-seg" role="group" aria-labelledby="speed-lbl">
            <button type="button" data-spd="1.3" aria-pressed="false">Slow</button>
            <button type="button" data-spd="2" class="on" aria-pressed="true">Normal</button>
            <button type="button" data-spd="3" aria-pressed="false">Fast</button>
          </div>
          <p class="hb-hint">How fast the birds fly; slow is calmer behind text.</p>
        </div>
        <div class="hb-setting">
          <label class="hb-switch-row"><span>Shows one bird's view</span><input class="hb-switch" type="checkbox" role="switch" id="view-tog" autocomplete="off"></label>
          <p class="hb-hint">Rings one bird and links it to the neighbors it follows.</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 flock of birds to [the section you want it behind]. Draw each bird as a small arrowhead on a canvas, pointing the way it flies. Each bird sees only the birds near it and follows three rules: keep a little room from the closest ones, turn the way its neighbors fly, and drift toward their middle, so the flock swirls and turns as one. Turn birds back before they reach the edges, and move them by the time since the last frame so the speed is the same on every screen. Use fewer birds on phones. When the settings include it, birds swerve away from the pointer or a finger. If the visitor has reduced motion turned on, show the flock 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 sections</li><li>Nature and travel sites</li><li>Art and game pages</li><li>Dark backgrounds</li></ul>
      <h3>Avoid on</h3>
      <ul class="hb-tags hb-avoid"><li>Long reading pages</li><li>Busy layouts</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 cvs=document.getElementById('cvs'),ctx=cvs.getContext('2d');
const stage=document.getElementById('stage');
const slowTog=document.getElementById('slow-tog');
const css=getComputedStyle(document.documentElement),BIRD=css.getPropertyValue('--bird'),LEAD=css.getPropertyValue('--lead');
const RED=css.getPropertyValue('--red'),BLUE=css.getPropertyValue('--blue'),GREEN=css.getPropertyValue('--green');
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
// Phones are screens up to 600px wide, or up to 500px tall when held sideways: they fly about half as many birds
const phone=matchMedia('(max-width:600px),(max-height:500px)');
const COUNTS={small:[70,35],medium:[150,70],large:[280,130]}; // [other screens, phones]
// How close they fly: the room each bird keeps around it (sep, in px) and the pull of the other two rules
const CLOSE={loose:{sep:32,align:.7,cohere:.3},normal:{sep:22,align:1,cohere:.5},tight:{sep:15,align:1.2,cohere:.9}};
let W=0,H=0,S=1,raf=null,lastT=null,paused=false;
let SIZE='medium',RULES=CLOSE.normal,SPD=2,FLEE=true,VIEW=false;
let birds=[];
const ptr={x:-1e4,y:-1e4},acc={x:0,y:0};
// See inside and Compare: the mode on show; Compare's two worlds (null outside Compare), one per half of the box; LONE is set while
// the world of birds with no rules steps or draws; pulls holds what bird 0's three rules added on its last move (rec: where step()
// writes it, only for Normal's flock); px,py is the pull steer() added last
let mode='normal',halves=null,LONE=false,px=0,py=0;
const NONE=[],pulls={n:0,F:1,ax:0,ay:0,cx:0,cy:0,sx:0,sy:0,mx:0,my:0};let rec=pulls;
const count=()=>COUNTS[SIZE][phone.matches?1:0];

function makeBird(){
  const a=Math.random()*Math.PI*2,v=SPD*S*(.6+Math.random()*.4);
  return {x:W*(.08+Math.random()*.84),y:H*(.08+Math.random()*.84),vx:Math.cos(a)*v,vy:Math.sin(a)*v};
}
// Reynolds steering: the change of velocity that turns bird b toward the direction (dx,dy) at full speed, at most F, times w
function steer(b,dx,dy,vmax,F,w){
  px=py=0;
  const d=Math.hypot(dx,dy);if(!d)return;
  let x=dx/d*vmax-b.vx,y=dy/d*vmax-b.vy;const l=Math.hypot(x,y);
  if(l>F){x*=F/l;y*=F/l;}
  px=x*w;py=y*w;acc.x+=px;acc.y+=py;
}
// One move, k 60 Hz frames long. Each bird heeds only the birds within R, not right behind it: it keeps apart (from those within
// sep), matches their direction and stays close (to their middle). Inside the margin M it turns back, harder nearer the edge (at most
// 30% of a narrow half). Bird 0's three pulls are written down as added. With LONE nobody has a neighbor: only the edge, the pointer and the speed limits act.
function step(k){
  const R=50*S,SEP=RULES.sep*S,vmax=SPD*S,vmin=vmax*.55,F=.045*SPD*S,M=Math.min(70*S,W*.3),E=F*2.4/M,RF=90*S;
  for(const b of birds){
    let n=0,cx=0,cy=0,ax=0,ay=0,sx=0,sy=0;
    const vb=Math.hypot(b.vx,b.vy),r=b===birds[0]?rec:null;
    for(const o of LONE?NONE:birds){
      if(o===b)continue;
      const dx=o.x-b.x,dy=o.y-b.y,d2=dx*dx+dy*dy;
      if(d2>R*R||dx*b.vx+dy*b.vy<-.5*vb*Math.sqrt(d2))continue;
      n++;cx+=o.x;cy+=o.y;ax+=o.vx;ay+=o.vy;
      if(d2<SEP*SEP&&d2>0){sx-=dx/d2;sy-=dy/d2;} // a closer neighbor pushes harder
    }
    acc.x=acc.y=0;
    if(r){r.n=n;r.F=F;r.ax=r.ay=r.cx=r.cy=0;r.mx=cx/n;r.my=cy/n;}
    if(n){steer(b,ax,ay,vmax,F,RULES.align);if(r){r.ax=px;r.ay=py;}steer(b,cx/n-b.x,cy/n-b.y,vmax,F,RULES.cohere);if(r){r.cx=px;r.cy=py;}}
    steer(b,sx,sy,vmax,F*1.5,2); // keeping apart may turn a bird three times as hard as the other two rules
    if(r){r.sx=px;r.sy=py;}
    if(b.x<M)acc.x+=(M-b.x)*E;else if(b.x>W-M)acc.x-=(b.x-W+M)*E;
    if(b.y<M)acc.y+=(M-b.y)*E;else if(b.y>H-M)acc.y-=(b.y-H+M)*E;
    if(FLEE){const dx=b.x-ptr.x,dy=b.y-ptr.y;if(dx*dx+dy*dy<RF*RF)steer(b,dx,dy,vmax,F*4,1);}
    b.vx+=acc.x*k;b.vy+=acc.y*k;
    const sp=Math.hypot(b.vx,b.vy)||1,lim=Math.min(vmax,Math.max(vmin,sp))/sp;
    b.vx*=lim;b.vy*=lim;b.x+=b.vx*k;b.y+=b.vy*k;
  }
}

function birdPath(b,L,w){ // an arrowhead pointing where the bird flies, added to the current path
  const sp=Math.hypot(b.vx,b.vy)||1,ux=b.vx/sp,uy=b.vy/sp;
  ctx.moveTo(b.x+ux*L,b.y+uy*L);
  ctx.lineTo(b.x-ux*L*.75-uy*w,b.y-uy*L*.75+ux*w);
  ctx.lineTo(b.x-ux*L*.35,b.y-uy*L*.35);
  ctx.lineTo(b.x-ux*L*.75+uy*w,b.y-uy*L*.75-ux*w);
  ctx.closePath();
}
// Every bird in one path; with hot (See inside), the birds that fail it are drawn again, faint
function drawBirds(hot){
  const L=5.5*S+1.5,w=3*S+.5;
  ctx.beginPath();birds.forEach(b=>{if(!hot||hot(b))birdPath(b,L,w);});
  ctx.fillStyle=BIRD;ctx.fill();
  if(!hot)return;
  ctx.beginPath();birds.forEach(b=>{if(!hot(b))birdPath(b,L,w);});
  ctx.globalAlpha=.3;ctx.fill();ctx.globalAlpha=1;
}
const sees=(b,o,R,vb)=>{const dx=o.x-b.x,dy=o.y-b.y,d2=dx*dx+dy*dy;return d2<=R*R&&dx*b.vx+dy*b.vy>=-.5*vb*Math.sqrt(d2);}; // step()'s test of a neighbor
function draw(){
  ctx.clearRect(0,0,W,H);
  if(halves)return drawHalves();
  if(mode==='inside'){const b=birds[0],R=50*S,vb=Math.hypot(b.vx,b.vy);drawBirds(o=>sees(b,o,R,vb));drawInside();return;}
  drawBirds();
  if(VIEW&&birds.length)drawView(true,.55);
}
// One bird's view: a line to every neighbor it follows (lines), the ring it looks within, the dashed room it keeps (not in the
// world with no rules) and the bird itself in orange, over whatever mid draws
function drawView(lines,alpha,mid){
  const b=birds[0],R=50*S,vb=Math.hypot(b.vx,b.vy),L=5.5*S+1.5,w=3*S+.5;
  ctx.strokeStyle=LEAD;ctx.lineWidth=1;ctx.globalAlpha=alpha;
  if(lines){ctx.beginPath();for(const o of birds)if(o!==b&&sees(b,o,R,vb)){ctx.moveTo(b.x,b.y);ctx.lineTo(o.x,o.y);}ctx.stroke();}
  ctx.beginPath();ctx.arc(b.x,b.y,R,0,Math.PI*2);ctx.stroke();
  if(!LONE){ctx.setLineDash([3,4]);ctx.beginPath();ctx.arc(b.x,b.y,RULES.sep*S,0,Math.PI*2);ctx.stroke();ctx.setLineDash([]);}
  ctx.globalAlpha=1;
  if(mid)mid();
  ctx.fillStyle=LEAD;ctx.beginPath();birdPath(b,L*1.3,w*1.3);ctx.fill();
}

// See inside: the view of bird 0 (its lines only with Shows one bird's view on), then an arrow from the bird for each rule, the
// pull that rule added on its last move, all on one scale (a full pull of the first two rules is 28px; keeping apart reaches three
// times as far), and a cross at the middle of the neighbors it follows. The key then moves off whatever this drew.
const key=stage.querySelector('.key');
function drawInside(){
  const b=birds[0],r=pulls,u=28*S/r.F,box=[b.x-50*S,b.y-50*S,b.x+50*S,b.y+50*S];
  drawView(VIEW,.7,()=>{
    [[r.sx,r.sy,RED],[r.ax,r.ay,BLUE],[r.cx,r.cy,GREEN]].forEach(([x,y,c])=>arrow(b.x,b.y,x*u,y*u,c,box));
    if(!r.n)return;
    ctx.strokeStyle=GREEN;ctx.lineWidth=2;ctx.beginPath();
    ctx.moveTo(r.mx-5,r.my);ctx.lineTo(r.mx+5,r.my);ctx.moveTo(r.mx,r.my-5);ctx.lineTo(r.mx,r.my+5);ctx.stroke();
  });
  const kw=key.offsetWidth,kh=key.offsetHeight;
  if(!kw)return;
  const hit=(right,low)=>{const x=right?W-10-kw:10,y=low?H-10-kh:10;return x<box[2]+6&&x+kw>box[0]-6&&y<box[3]+6&&y+kh>box[1]-6;};
  let right=key.classList.contains('right'),low=key.classList.contains('low');
  for(const[rt,lw]of[[right,low],[false,false],[true,false],[false,true],[true,true]])if(!hit(rt,lw)){right=rt;low=lw;break;}
  key.classList.toggle('right',right);key.classList.toggle('low',low);
}
function arrow(x0,y0,dx,dy,col,box){ // a line with a head from (x0,y0) by (dx,dy); box grows to hold its tip
  const len=Math.hypot(dx,dy);if(len<3)return;
  const x1=x0+dx,y1=y0+dy,ux=dx/len,uy=dy/len,h=Math.min(8*S+2,len*.6);
  ctx.strokeStyle=ctx.fillStyle=col;ctx.lineWidth=2.5;
  ctx.beginPath();ctx.moveTo(x0,y0);ctx.lineTo(x1-ux*h,y1-uy*h);ctx.stroke();
  ctx.beginPath();ctx.moveTo(x1,y1);ctx.lineTo(x1-ux*h-uy*h*.5,y1-uy*h+ux*h*.5);ctx.lineTo(x1-ux*h+uy*h*.5,y1-uy*h-ux*h*.5);ctx.closePath();ctx.fill();
  box[0]=Math.min(box[0],x1);box[1]=Math.min(box[1],y1);box[2]=Math.max(box[2],x1);box[3]=Math.max(box[3],y1);
}

// Compare: two worlds, one for each half of the box below its name (no bird flies under it), each with half the birds so it is as
// crowded as Normal. Both start from the same birds (places as shares of the world, headings and speeds from a fixed seed), fly the
// same 180 moves and then take the same moves from the loop's one clock; the first half's birds follow no rules (LONE).
const halfName=stage.querySelector('.half');
function makeHalves(){
  const hw=W/2,top=Math.min(halfName.offsetTop+halfName.offsetHeight+8,H/3),h=H-top;let a=20261022;
  const rnd=()=>{a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;};
  const start=Array.from({length:Math.round(count()/2)},()=>[rnd(),rnd(),rnd()*Math.PI*2,.6+rnd()*.4]);
  halves=[true,false].map(lone=>({W:hw,H:h,top,lone,birds:start.map(([fx,fy,t,f])=>{
    const v=SPD*S*f;return{x:hw*(.08+.84*fx),y:h*(.08+.84*fy),vx:Math.cos(t)*v,vy:Math.sin(t)*v};})}));
  halves.forEach(o=>inWorld(o,()=>{for(let i=0;i<180;i++)step(1);}));
}
// Runs fn as if a world were the page's: its birds, size and rules (or none), nothing recorded, and the pointer in that world's own place
function inWorld(o,fn){
  const was=[birds,W,H,LONE,rec,ptr.x,ptr.y];
  birds=o.birds;W=o.W;H=o.H;LONE=o.lone;rec=null;if(ptr.x>=o.W)ptr.x-=o.W;ptr.y-=o.top;
  fn();
  [birds,W,H,LONE,rec,ptr.x,ptr.y]=was;
}
// Each world is clipped to itself (below its half's name); a faint ring in both marks where the pointer is in its half, so both flee the same spot
function drawHalves(){
  const hw=W/2;
  halves.forEach((o,i)=>{
    ctx.save();ctx.beginPath();ctx.rect(i*hw,o.top,hw,o.H);ctx.clip();ctx.translate(i*hw,o.top);
    inWorld(o,()=>{
      drawBirds();
      if(VIEW)drawView(!LONE,.55);
      if(FLEE&&ptr.x>-1e3){ctx.strokeStyle='rgba(236,240,255,.4)';ctx.lineWidth=1;ctx.setLineDash([4,5]);ctx.beginPath();ctx.arc(ptr.x,ptr.y,90*S,0,Math.PI*2);ctx.stroke();ctx.setLineDash([]);}
    });
    ctx.restore();
  });
  ctx.fillStyle='rgba(236,240,255,.3)';ctx.fillRect(hw-1,0,2,H);
}

// A fresh flock flies 3 seconds out of sight first, so even the first picture (and the still one under reduced motion) shows flocks
function spawn(){birds=Array.from({length:count()},makeBird);for(let i=0;i<180;i++)step(1);draw();}
// Flock size and the phone limit add birds at random places (they join a flock in a few seconds) or take the last ones away; Compare
// starts both halves again from its seed with the new count
function recount(){
  const n=count();
  while(birds.length<n)birds.push(makeBird());
  birds.length=n;
  if(halves)makeHalves();
  refresh();
}
// Paused, a changed setting shows at once: Compare (with again) starts its halves again from the seed, and See inside works bird 0's
// pulls out again where the birds are (a move of no length)
function refresh(again){if(!paused)return;if(again&&halves)makeHalves();if(mode==='inside')step(0);draw();}

// loop() keeps exactly one frame requested in raf; Pause cancels it and Play starts one loop again. At most one frame per 16 ms
// flies the time since the last one (at most 50 ms, a third in slow motion); a first frame after a start only takes the time.
function loop(ts){
  raf=requestAnimationFrame(loop);
  if(lastT!==null&&ts-lastT<16)return;
  const dt=lastT===null?0:Math.min(ts-lastT,50);
  lastT=ts;
  if(dt)advance(dt/FRAME*(slowTog.checked?1/3:1));
  draw();
}
// A long frame is flown as equal moves of at most 1.05 of a 60 Hz frame, so a bird turns no harder in one move on a 30 Hz screen.
// In Compare both halves take each move, so they always fly the same time.
function advance(k){const n=Math.max(1,Math.ceil(k-.05));for(let i=0;i<n;i++){if(halves)halves.forEach(o=>inWorld(o,()=>step(k/n)));else step(k/n);}}
function start(){if(raf)return;lastT=null;raf=requestAnimationFrame(loop);}

// At the top level, before the deferred shared script runs: under reduced motion it pauses the loop on arrival. Paused birds stay put.
document.addEventListener('hb:pause',e=>{
  paused=e.detail.paused;
  if(paused){cancelAnimationFrame(raf);raf=null;}
  else start();
  notes();
});
// A tab that comes back after being hidden has no earlier frame to measure from, so its first frame moves nothing
document.addEventListener('visibilitychange',()=>{lastT=null;});

// The mode switch draws the mode at once, paused or not. See inside draws over Normal's own flock, which goes on as it is; Compare
// leaves Normal's birds where they are (they are not moved, or drawn, until Normal comes back) and starts its halves once.
const NAMES={normal:cvs.getAttribute('aria-label'),
  inside:'The flock with one bird ringed: arrows show its three pulls, keep apart, fly the same way and stay close',
  compare:'Two skies side by side: on the left birds with no flock rules scatter, on the right the same birds fly as flocks'};
document.addEventListener('hb:mode',e=>{
  mode=e.detail.mode;
  cvs.setAttribute('aria-label',NAMES[mode]);
  if(mode!=='compare')halves=null;
  else if(!halves)makeHalves();
  if(paused&&mode==='inside')step(0);
  draw();
});
// The notes as the markup writes them; shown still (reduced motion, paused) they say what the still shows, and give way to the
// moving ones while the birds fly
const noteIn=document.querySelector('[data-hb-for="inside"]'),noteCmp=document.querySelector('[data-hb-for="compare"]');
const NOTES={inside:noteIn.textContent,compare:noteCmp.textContent,
  stillIn:'Shown still: one bird (orange) sees only the birds in its ring (the rest fade); its three pulls are keep apart (red), fly the same way (blue) and stay close (green).',
  stillCmp:'Shown still, from the same start: On their own, the birds have scattered every which way; As a flock, they fly in groups.'};
const reduced=matchMedia('(prefers-reduced-motion: reduce)');
function notes(){ // written only when the words change, so the live region does not read a note again at every Pause and Play
  const still=paused&&reduced.matches,put=(el,t)=>{if(el.textContent!==t)el.textContent=t;};
  put(noteIn,still?NOTES.stillIn:NOTES.inside);put(noteCmp,still?NOTES.stillCmp:NOTES.compare);
}
reduced.addEventListener('change',notes);

// Setting the canvas size wipes it, so a real change of the stage's size draws the flock again at once: the first starts the flock,
// later ones stretch it. A resize that leaves the stage as it was (a phone's address bar sliding in or out) does nothing.
function resize(){
  const w=stage.clientWidth,h=stage.clientHeight;
  if(w===W&&h===H)return;
  if(W)birds.forEach(b=>{b.x*=w/W;b.y*=h/H;});
  W=w;H=h;S=Math.min(1,Math.max(.65,Math.min(W,H)/380));
  const dpr=Math.min(window.devicePixelRatio||1,2);
  cvs.width=W*dpr;cvs.height=H*dpr;ctx.setTransform(dpr,0,0,dpr,0,0);
  if(halves)makeHalves();
  if(birds.length){if(paused&&mode==='inside')step(0);draw();}else spawn(); // paused See inside works its pulls out again for the new size
}

// The pointer is recorded even while paused; the birds react to it only when they move (a paused Compare moves its rings). A mouse
// or pen uses pointer events; a finger uses touch events, so it keeps working while the page scrolls.
function aim(x,y){const r=cvs.getBoundingClientRect();ptr.x=x-r.left;ptr.y=y-r.top;if(halves&&paused)draw();}
function away(){ptr.x=ptr.y=-1e4;if(halves&&paused)draw();}
stage.addEventListener('pointermove',e=>{if(e.pointerType!=='touch')aim(e.clientX,e.clientY);});
stage.addEventListener('pointerleave',e=>{if(e.pointerType!=='touch')away();});
const finger=e=>aim(e.touches[0].clientX,e.touches[0].clientY);
stage.addEventListener('touchstart',finger,{passive:true});
stage.addEventListener('touchmove',finger,{passive:true});
['touchend','touchcancel'].forEach(t=>stage.addEventListener(t,away));

function choices(id,pick){
  const buttons=document.querySelectorAll('#'+id+' button');
  buttons.forEach(b=>b.addEventListener('click',()=>{
    if(b.classList.contains('on'))return; // pressing the choice already made does nothing
    buttons.forEach(x=>{x.classList.toggle('on',x===b);x.setAttribute('aria-pressed',String(x===b))});
    pick(b.dataset);
  }));
}
choices('size-seg',d=>{SIZE=d.size;recount();});
choices('close-seg',d=>{RULES=CLOSE[d.close];refresh(true);});
// A new speed scales every bird's speed, so the flock carries on smoothly instead of jumping to the new limits
choices('speed-seg',d=>{const n=+d.spd,r=n/SPD;SPD=n;[birds,...(halves||[]).map(o=>o.birds)].forEach(l=>l.forEach(b=>{b.vx*=r;b.vy*=r;}));refresh(true);});
document.getElementById('flee-tog').addEventListener('change',e=>{FLEE=e.target.checked;refresh();});
document.getElementById('view-tog').addEventListener('change',e=>{VIEW=e.target.checked;refresh();});

resize();
window.addEventListener('resize',resize);
if(phone.addEventListener)phone.addEventListener('change',recount);
else if(phone.addListener)phone.addListener(recount);
start();
</script>
</body>
</html>