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.

feat: Flocking shows one bird's ring with arrows for its three pulls (See inside) and On their own beside As a flock (Compare)

matin437ae947c408
diff --git a/animations/06-3d-advanced/flocking/index.html b/animations/06-3d-advanced/flocking/index.html
index e18c4222..6a33ad09 100644
--- a/animations/06-3d-advanced/flocking/index.html
+++ b/animations/06-3d-advanced/flocking/index.html
@@ -21,10 +21,24 @@
<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}
+ :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=10">
<script src="../../../assets/js/demo-page.js?v=10" defer></script>
@@ -47,13 +61,30 @@
<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">
@@ -148,6 +179,7 @@ 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)');
@@ -158,6 +190,12 @@ 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);
@@ -165,19 +203,21 @@ function makeBird(){
}
// 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;}
- acc.x+=x*w;acc.y+=y*w;
+ 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.
+// 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=70*S,E=F*2.4/M,RF=90*S;
+ 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);
- for(const o of birds){
+ 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;
@@ -185,8 +225,10 @@ function step(k){
if(d2<SEP*SEP&&d2>0){sx-=dx/d2;sy-=dy/d2;} // a closer neighbor pushes harder
}
acc.x=acc.y=0;
- if(n){steer(b,ax,ay,vmax,F,RULES.align);steer(b,cx/n-b.x,cy/n-b.y,vmax,F,RULES.cohere);}
+ 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);}
@@ -204,32 +246,111 @@ function birdPath(b,L,w){ // an arrowhead pointing where the bird flies, added t
ctx.lineTo(b.x-ux*L*.75+uy*w,b.y-uy*L*.75-ux*w);
ctx.closePath();
}
-function draw(){
- ctx.clearRect(0,0,W,H);
+// 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=>birdPath(b,L,w));
+ ctx.beginPath();birds.forEach(b=>{if(!hot||hot(b))birdPath(b,L,w);});
ctx.fillStyle=BIRD;ctx.fill();
- if(!VIEW||!birds.length)return;
- // One bird's view: the ring it looks within, the dashed room it keeps, and a line to every neighbor it follows
- const b=birds[0],R=50*S,vb=Math.hypot(b.vx,b.vy);
- ctx.strokeStyle=LEAD;ctx.lineWidth=1;ctx.globalAlpha=.55;ctx.beginPath();
- for(const o of birds){const dx=o.x-b.x,dy=o.y-b.y,d2=dx*dx+dy*dy; // the same test as in step(): within R, not right behind
- if(o!==b&&d2<=R*R&&dx*b.vx+dy*b.vy>=-.5*vb*Math.sqrt(d2)){ctx.moveTo(b.x,b.y);ctx.lineTo(o.x,o.y);}}
- ctx.stroke();
+ 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();
- 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;ctx.fillStyle=LEAD;ctx.beginPath();birdPath(b,L*1.3,w*1.3);ctx.fill();
+ 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, each with half the birds so it is as crowded as Normal. Both start from the
+// same birds (places as shares of the half, 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). Normal's own birds are not touched meanwhile.
+function makeHalves(){
+ const hw=W/2;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,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 half's own place
+function inWorld(o,fn){
+ const was=[birds,W,H,LONE,rec,ptr.x];
+ birds=o.birds;W=o.W;H=o.H;LONE=o.lone;rec=null;if(ptr.x>=o.W)ptr.x-=o.W;
+ fn();
+ [birds,W,H,LONE,rec,ptr.x]=was;
+}
+// Each half is clipped to itself; 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,0,hw,H);ctx.clip();ctx.translate(i*hw,0);
+ 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:COUNTS[SIZE][phone.matches?1:0]},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
+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=COUNTS[SIZE][phone.matches?1:0];
+ const n=count();
while(birds.length<n)birds.push(makeBird());
birds.length=n;
- if(paused)draw();
+ 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.
@@ -241,8 +362,9 @@ function loop(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
-function advance(k){const n=Math.max(1,Math.ceil(k-.05));for(let i=0;i<n;i++)step(k/n);}
+// 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.
@@ -250,10 +372,34 @@ 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(){const still=paused&&reduced.matches;noteIn.textContent=still?NOTES.stillIn:NOTES.inside;noteCmp.textContent=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(){
@@ -263,13 +409,14 @@ function resize(){
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)draw();else spawn();
}
-// The pointer is recorded even while paused; the birds react to it only when they move. 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;}
-function away(){ptr.x=ptr.y=-1e4;}
+// 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);
@@ -286,11 +433,11 @@ function choices(id,pick){
}));
}
choices('size-seg',d=>{SIZE=d.size;recount();});
-choices('close-seg',d=>{RULES=CLOSE[d.close];});
+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.forEach(b=>{b.vx*=r;b.vy*=r;});});
-document.getElementById('flee-tog').addEventListener('change',e=>{FLEE=e.target.checked;});
-document.getElementById('view-tog').addEventListener('change',e=>{VIEW=e.target.checked;if(paused)draw();});
+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);