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.

35.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>Canvas Particle Effect — Animation Handbook</title>
  <meta name="description" content="Dots drift, link up when close, and dodge your pointer. Best for tech sites.">
  <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/canvas-particle-effect/">
  <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="Canvas Particle Effect — Animation Handbook">
  <meta property="og:description" content="Dots drift, link up when close, and dodge your pointer. Best for tech sites.">
  <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/canvas-particle-effect/">
  <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="Canvas Particle Effect — Animation Handbook">
  <meta name="twitter:description" content="Dots drift, link up when close, and dodge your pointer. Best for tech sites.">
  <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": "Canvas Particle Effect", "name": "Canvas Particle Effect", "description": "Dots drift, link up when close, and dodge your pointer. Best for tech sites.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/canvas-particle-effect/", "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, Canvas Particle Effect"}</script>
  <style>
    :root{--ui-accent:#3fd6c4}
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    .stage{position:relative;overflow:hidden;background:#060a10}
    canvas{display:block;width:100%;height:100%}
    /* See inside and Compare: a second canvas for the marks, and plain words over the picture */
    .marks{position:absolute;inset:0;display:none;pointer-events:none}
    .lbl{position:absolute;display:none;padding:4px 9px;border-radius:999px;background:rgba(6,10,16,.92);color:#f4f4f2;font:600 13px/1.2 var(--hb-font);white-space:nowrap;pointer-events:none}
    .sh{display:none}
    .stage[data-hb-mode="inside"] .marks,.stage[data-hb-mode="inside"] .cap:not([hidden]),.stage[data-hb-mode="compare"] .side{display:block}
    .side{top:10px;left:10px}
    .side.second{left:calc(50% + 11px)}
    @media(max-width:900px),(max-height:500px){.lg{display:none}.sh{display:inline}}
  </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="../parallax-3d-tilt/" rel="prev" aria-label="Previous: Parallax 3D Tilt"><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>Parallax 3D Tilt</span></a><a href="../fluid-simulation/" rel="next" aria-label="Next: Fluid / Liquid Simulation"><span><span class="hb-dir">Next: </span>Fluid / Liquid Simulation</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.04 · 3D &amp; Advanced</p>
    <h1>Canvas Particle Effect</h1>
    <p class="hb-lede">Dots drift, link up when close, and dodge your pointer. Best for tech sites.</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 dots move 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 dots drifting on a dark background, joined by thin lines when they come close"></canvas>
      <canvas class="marks" id="marks" aria-hidden="true"></canvas>
      <p class="lbl cap a" aria-hidden="true" data-hb-caption><span class="lg">Dashed ring: a ringed dot joins every dot inside it</span><span class="sh">Dashed ring: joins dots inside</span></p>
      <p class="lbl cap b" aria-hidden="true" data-hb-caption><span class="lg">Arrow: each dot drifts its own way, bouncing off the edges</span><span class="sh">Arrow: how each dot drifts</span></p>
      <p class="lbl cap c" aria-hidden="true" data-hb-caption>Pointer pushes dots away</p>
      <p class="lbl cap d" aria-hidden="true" data-hb-caption>Lines fade as the dots move apart</p>
      <p class="lbl side first" aria-hidden="true" data-hb-caption>Dots only</p>
      <p class="lbl side second" aria-hidden="true" data-hb-caption>With links</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 dot drifts its own way and joins every dot inside its dashed ring with a line. The pointer pushes away dots inside its own ring; point at the box to move it.</p>
      <p data-hb-for="compare" hidden>Dots only and With links are the same dots moving the same way. Only the lines differ: they join dots that come close, which turns the dots into a network.</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="force-lbl">Pointer effect</p>
        <div class="seg" id="force-seg" role="group" aria-labelledby="force-lbl">
          <button type="button" data-force="-0.5" class="on" aria-pressed="true">Push</button>
          <button type="button" data-force="0.5" aria-pressed="false">Pull</button>
          <button type="button" data-force="0" aria-pressed="false">None</button>
        </div>
        <p class="hb-hint">What your pointer or finger does to nearby dots.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="count-lbl">Number of particles</p>
        <div class="seg" id="count-seg" role="group" aria-labelledby="count-lbl">
          <button type="button" data-level="0" aria-pressed="false">Few</button>
          <button type="button" data-level="1" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-level="2" aria-pressed="false">Many</button>
        </div>
        <p class="hb-hint">More dots make more links; phones and tablets draw fewer.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="link-lbl">Link distance</p>
        <div class="seg" id="link-seg" role="group" aria-labelledby="link-lbl">
          <button type="button" data-dist="0" aria-pressed="false">None</button>
          <button type="button" data-dist="70" aria-pressed="false">Short</button>
          <button type="button" data-dist="100" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-dist="150" aria-pressed="false">Long</button>
        </div>
        <p class="hb-hint">How close two dots must be to join with a line.</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="0.5" aria-pressed="false">Slow</button>
            <button type="button" data-spd="0.8" class="on" aria-pressed="true">Normal</button>
            <button type="button" data-spd="1.3" aria-pressed="false">Fast</button>
          </div>
          <p class="hb-hint">Slow drifting feels calm; fast looks busy.</p>
        </div>
        <div class="hb-setting">
          <p class="hb-setting-name" id="color-lbl">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 dots and lines.</p>
        </div>
        <div class="hb-setting">
          <label class="hb-switch-row"><span>Trails</span><input class="hb-switch" type="checkbox" role="switch" id="trail-tog" autocomplete="off"></label>
          <p class="hb-hint">Each dot leaves a fading streak behind it.</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 particle background to [the section you want it behind]. Draw small dots on a canvas, give each its own direction, and bounce them off the edges. When the settings include lines, join any two dots that come close with a thin line that fades as they move apart, so a network keeps forming and breaking. Dots near the pointer, or a finger on touch screens, can be pushed away or pulled in. Checking every pair of dots gets slow quickly, so draw far fewer dots on phones and tablets, and stroke the lines in a few batches rather than one at a time. If the visitor has reduced motion turned on, show the dots 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>Tech sites</li><li>Loading screens</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');const ctx=cvs.getContext('2d');
const stage=document.getElementById('stage');
const slowTog=document.getElementById('slow-tog');
let W,H,particles=[],mouse={x:-999,y:-999};
let paused=false,raf=null,last=null;
let COUNT=500,level=1,DIST=100,SPD=0.8,FORCE=-0.5,COLOR='#58a6ff';
let CONNECTIONS=true,TRAILS=false;
// Dots for Few, Medium and Many on wide screens, on screens up to 1024px, and on phones (up to 600px wide, or up to 500px tall)
const COUNTS=[[250,500,800],[60,90,120],[30,45,60]];

// See inside draws its marks on a second canvas, cleared and drawn again after every drawn frame, so Trails cannot smear them. Compare
// draws a new set of dots twice on the one canvas, in a world half the box wide (WW by WH, below the names) and keeps Normal's in kept.
const marks=document.getElementById('marks'),mctx=marks.getContext('2d');
const keep=document.createElement('canvas'),kctx=keep.getContext('2d');
const phoneQ=matchMedia('(max-width:600px),(max-height:500px)');
const REACH=120,TOP=40,DASH=[6,5],NONE=[],CUR=new Path2D('M0 0L0 16L4 12L7 19L9.5 18L6.5 11L12 11Z'),ra=[0,0,0,0];
let mode='normal',kept=null,follow=[],raw={x:-999,y:-999},park={x:0,y:0},parked=false,WW=0,WH=0,HW=0,dpr=1;

// Backing store is scaled by DPR (capped at 2) so 0.5px lines and 1px dots stay crisp
// on retina screens; the context transform keeps all drawing in CSS pixels.
function resize(){
  dpr=Math.min(window.devicePixelRatio||1,2);
  W=stage.clientWidth;H=stage.clientHeight;
  cvs.width=marks.width=Math.round(W*dpr);cvs.height=marks.height=Math.round(H*dpr);
  ctx.setTransform(dpr,0,0,dpr,0,0);mctx.setTransform(dpr,0,0,dpr,0,0);
  setWorld();
  park.x=W>2*REACH+12?Math.min(W*.66,W-REACH-6):W/2;park.y=H/3; // See inside parks a pretend pointer here, its whole ring in the box when it fits
}
function setWorld(){if(mode==='compare'){HW=Math.floor((W-2)/2);WW=HW;WH=H-TOP;}else{WW=W;WH=H;}}

class P{
  constructor(){this.reset();}
  reset(){
    this.x=Math.random()*WW;this.y=Math.random()*WH;
    const a=Math.random()*Math.PI*2;const s=(.2+Math.random()*.8)*SPD;
    this.vx=Math.cos(a)*s;this.vy=Math.sin(a)*s;
    this.r=Math.random()*1.5+.5;this.op=.3+Math.random()*.7;
  }
  // k counts steps of 1/60 s: 1 for a frame on a 60 Hz screen, more for a longer frame, and a third of that while Slow motion is on
  update(k){
    const dx=this.x-mouse.x,dy=this.y-mouse.y;
    const d2=dx*dx+dy*dy;
    // (dx,dy)/d points away from the pointer, so subtracting FORCE makes
    // negative = push away and positive = pull in, matching the Pointer effect setting.
    if(d2<14400&&d2>1){const d=Math.sqrt(d2);this.vx-=FORCE*(dx/d)/d*.8*k;this.vy-=FORCE*(dy/d)/d*.8*k;}
    const maxV=SPD*2;const sp=Math.sqrt(this.vx*this.vx+this.vy*this.vy);
    if(sp>maxV){this.vx=this.vx/sp*maxV;this.vy=this.vy/sp*maxV;}
    this.x+=this.vx*k;this.y+=this.vy*k;
    if(this.x<0){this.x=0;this.vx*=-1;}if(this.x>WW){this.x=WW;this.vx*=-1;}
    if(this.y<0){this.y=0;this.vy*=-1;}if(this.y>WH){this.y=WH;this.vy*=-1;}
  }
}

// The number of dots depends on the size of the screen, checked at each spawn(): far fewer on tablets and on phones,
// which are up to 600px wide, or up to 500px tall when held sideways. Compare's world is half the box, so it gets half the dots.
// See inside follows the dots nearest a quarter, a half and three quarters across, at mid-height.
function spawn(){
  COUNT=COUNTS[innerWidth<=600||innerHeight<=500?2:innerWidth<=1024?1:0][level];
  if(mode==='compare')COUNT>>=1;
  particles=[];
  for(let i=0;i<COUNT;i++)particles.push(new P());
  follow=mode==='compare'?[]:[.25,.5,.75].map(f=>{
    let best=null,bd=Infinity;
    for(const p of particles){const d=(p.x-W*f)**2+(p.y-H/2)**2;if(d<bd){bd=d;best=p;}}
    return best;
  });
}

// Lines (when links is true and Link distance is not None), then the dots; dim fades both (See inside dims every dot but the followed ones)
function paint(links,dim){
  const hex=COLOR,r=parseInt(hex.slice(1,3),16),g=parseInt(hex.slice(3,5),16),b=parseInt(hex.slice(5,7),16);

  // Connections: every link goes into one of six paths by its opacity step, and each path is stroked once
  if(links&&CONNECTIONS){
    const d2max=DIST*DIST;
    const paths=Array.from({length:6},()=>new Path2D());
    for(let i=0;i<particles.length;i++){
      for(let j=i+1;j<particles.length;j++){
        const dx=particles[i].x-particles[j].x,dy=particles[i].y-particles[j].y;
        const d2=dx*dx+dy*dy;
        if(d2<d2max){
          const k=Math.min(5,Math.floor((1-d2/d2max)*6));
          paths[k].moveTo(particles[i].x,particles[i].y);paths[k].lineTo(particles[j].x,particles[j].y);
        }
      }
    }
    ctx.lineWidth=.5;
    paths.forEach((path,k)=>{
      ctx.strokeStyle=`rgba(${r},${g},${b},${(k+.5)/6*.4*dim})`;
      ctx.stroke(path);
    });
  }

  // Dots
  particles.forEach(p=>{
    ctx.fillStyle=`rgba(${r},${g},${b},${p.op*dim})`;
    ctx.beginPath();ctx.arc(p.x,p.y,p.r,0,Math.PI*2);ctx.fill();
  });
}

// washes is how many times the Trails wash (15% of the old picture) is laid over it: once for a frame at 60 Hz
function draw(washes=1){
  if(TRAILS){ctx.fillStyle='rgba(6,10,16,.15)';for(let i=0;i<washes;i++)ctx.fillRect(0,0,W,H);}
  else{ctx.clearRect(0,0,W,H);}
  if(mode!=='compare')return paint(true,mode==='inside'?.5:1);
  // Compare: the same dots twice, each half clipped; only the second joins them with lines
  for(let s=0;s<2;s++){
    ctx.save();ctx.translate(s*(HW+2),TOP);ctx.beginPath();ctx.rect(0,0,HW,WH);ctx.clip();
    paint(s===1,1);ctx.restore();
  }
  ctx.fillStyle='#2f3743';ctx.fillRect(HW,0,2,H);
}

// One of the pointer ring's eight arrows into ra: out from the ring's inside for Push, in for Pull
function reach(i,x,y){
  const a=Math.PI/8+i*Math.PI/4,c=Math.cos(a),s=Math.sin(a),o=FORCE<0;
  ra[0]=x+c*(o?103:118);ra[1]=y+s*(o?103:118);ra[2]=x+c*(o?118:103);ra[3]=y+s*(o?118:103);
}
function arrow(x0,y0,x1,y1){
  const a=Math.atan2(y1-y0,x1-x0);
  mctx.moveTo(x0,y0);mctx.lineTo(x1,y1);
  mctx.lineTo(x1-Math.cos(a-.5)*6,y1-Math.sin(a-.5)*6);mctx.moveTo(x1,y1);mctx.lineTo(x1-Math.cos(a+.5)*6,y1-Math.sin(a+.5)*6);
}
// See inside, from the page's own numbers: each followed dot gets a dashed ring as wide as Link distance, its own links brighter and an
// arrow as long as it drifts in a second; the pointer gets a ring as wide as its reach, eight arrows out (Push) or in (Pull) and a cursor
function drawMarks(){
  dodge();mctx.clearRect(0,0,W,H);mctx.lineCap='round';
  const r=parseInt(COLOR.slice(1,3),16),g=parseInt(COLOR.slice(3,5),16),b=parseInt(COLOR.slice(5,7),16);
  for(let i=phoneQ.matches?1:0,n=phoneQ.matches?2:3;i<n;i++){
    const p=follow[i];if(!p)continue;
    if(CONNECTIONS){
      const d2max=DIST*DIST;mctx.lineWidth=1.25;
      for(let k=0;k<6;k++){
        mctx.strokeStyle=`rgba(${r},${g},${b},${Math.min(1,(k+.5)/6*.4*2.5)})`;mctx.beginPath();
        for(const q of particles){
          const dx=q.x-p.x,dy=q.y-p.y,d2=dx*dx+dy*dy;
          if(q!==p&&d2<d2max&&Math.min(5,Math.floor((1-d2/d2max)*6))===k){mctx.moveTo(p.x,p.y);mctx.lineTo(q.x,q.y);}
        }
        mctx.stroke();
      }
      mctx.setLineDash(DASH);mctx.strokeStyle=`rgb(${r},${g},${b})`;mctx.lineWidth=1.5;
      mctx.beginPath();mctx.arc(p.x,p.y,DIST,0,Math.PI*2);mctx.stroke();mctx.setLineDash(NONE);
    }
    mctx.fillStyle=`rgb(${r},${g},${b})`;mctx.strokeStyle='#f4f4f2';mctx.lineWidth=1.2;
    mctx.beginPath();mctx.arc(p.x,p.y,p.r+2.5,0,Math.PI*2);mctx.fill();mctx.stroke();
    const v=Math.hypot(p.vx,p.vy)||1,s0=p.r+4,len=Math.max(v*60,s0+10);
    mctx.lineWidth=2;mctx.beginPath();arrow(p.x+p.vx/v*s0,p.y+p.vy/v*s0,p.x+p.vx/v*len,p.y+p.vy/v*len);mctx.stroke();
  }
  if(!FORCE)return;
  const x=mouse.x,y=mouse.y;
  mctx.setLineDash(DASH);mctx.strokeStyle='#ffd666';mctx.lineWidth=1.5;
  mctx.beginPath();mctx.arc(x,y,REACH,0,Math.PI*2);mctx.stroke();mctx.setLineDash(NONE);
  mctx.lineWidth=2;mctx.beginPath();
  for(let i=0;i<8;i++){reach(i,x,y);arrow(ra[0],ra[1],ra[2],ra[3]);}
  mctx.stroke();
  if(parked){mctx.save();mctx.translate(x,y);mctx.fillStyle='#fff';mctx.strokeStyle='#060a10';mctx.lineWidth=1.2;mctx.fill(CUR);mctx.stroke(CUR);mctx.restore();}
}

// One step is 1/60 s, so the dots drift at the same speed whatever the screen's refresh rate.
const FRAME=1000/60;
// The loop looks at every frame the screen offers and draws only when a Trails wash is due. "steps" is the time since the last
// drawn frame in steps of 1/60 s (a gap counts for at most 50 ms); "due" is the same, except that a value within 5% of a whole
// number counts as that number, so a screen a little off 60 Hz, or a little unsteady, still washes exactly once a frame. "owed"
// adds the steps up, and a wash is due once Math.round(owed + .05) reaches 1 (twice on a 30 Hz screen); the .05 keeps half a step,
// which is what a frame is at exactly 120 or 240 Hz, from sitting on a tie that timestamp noise could decide either way. A frame
// with no wash due draws nothing and changes nothing, so its time carries to the next frame; that keeps the drawing near 60
// pictures a second on faster screens. A drawn frame moves the dots by all the time since the last one, and by a third of that while Slow motion is on, and
// lays the wash over the picture once for every step due, always at the same 15%; Slow motion does not slow it: a smaller wash
// is rounded differently by the 8-bit canvas, and the faint leftovers of a trail would end up another color. A tab that comes
// back to the front starts again from its next frame, so the time away adds no step.
let owed=0;
function loop(t){
  raf=requestAnimationFrame(loop);
  if(last===null){last=t;return;} // the first frame after a start only takes the time
  const steps=Math.min(t-last,50)/FRAME,whole=Math.max(1,Math.round(steps)),due=Math.abs(steps-whole)<.05?whole:steps;
  if(Math.round(owed+due+.05)<1)return;
  last=t;
  particles.forEach(p=>p.update(steps*(slowTog.checked?1/3:1)));
  owed+=due;const washes=Math.round(owed+.05);owed-=washes;
  draw(washes);
  if(mode==='inside')drawMarks();
}
function start(){if(raf)return;last=null;owed=0;raf=requestAnimationFrame(loop);}
document.addEventListener('visibilitychange',()=>{last=null;owed=0;});
// While paused a setting or a resize draws the picture again, so the change shows without anything moving. The canvas is
// cleared first: with Trails on, draw() only lays a thin wash over the old picture, which would stay showing under the new one.
function redraw(){if(paused){ctx.clearRect(0,0,W,H);draw();}}

// Registered at the top level, before the shared script (deferred) can run: under reduced motion it pauses the
// loop on arrival, which this listener must catch. Pause cancels the pending frame and the picture stays;
// Play calls start(), which carries on from the current positions.
document.addEventListener('hb:pause',e=>{
  paused=e.detail.paused;
  if(paused){cancelAnimationFrame(raf);raf=null;}
  else start();
  notes();
});

// The captions: placed from their measured sizes at a mode, a setting, a resize or when the font arrives (never per frame), each in the
// first spot that meets no other caption and none of the pointer's arrows. The pointer's caption shows only while its cursor is parked.
const cap=k=>stage.querySelector('.cap.'+k),capA=cap('a'),capB=cap('b'),capC=cap('c'),capD=cap('d');
const put=(el,t)=>{if(el.textContent!==t)el.textContent=t;};
// want[i]: caption i belongs in this view; gone[i]: a followed dot is near it, so it steps aside; spot[i]: where place() put it
const caps=[capA,capB,capC,capD],want=[0,0,0,0],gone=[0,0,0,0],spot=[null,null,null,null];
let roomC=true;
function place(){
  capA.hidden=!CONNECTIONS;capB.hidden=false;capD.hidden=phoneQ.matches||!CONNECTIONS;capC.hidden=!FORCE;spot.fill(null);
  put(capC,FORCE<0?'Pointer pushes dots away':'Pointer pulls dots in');
  const M=10,R=REACH+8,cx=park.x,cy=park.y,hb=capB.offsetHeight,fixed=[],boxes=[];
  roomC=true;
  if(FORCE){
    for(let i=0;i<8;i++){reach(i,cx,cy);fixed.push([Math.min(ra[0],ra[2])-4,Math.min(ra[1],ra[3])-4,Math.max(ra[0],ra[2])+4,Math.max(ra[1],ra[3])+4]);}
    fixed.push([cx-3,cy-3,cx+14,cy+20]);
  }
  for(const p of seen()){const [x,y]=tip(p),m=p.r+3+18;fixed.push([Math.min(p.x,x)-m,Math.min(p.y,y)-m,Math.max(p.x,x)+m,Math.max(p.y,y)+m]);}
  const list=[
    [capC,(w,h)=>[[cx-w/2,cy+R],[cx-w/2,cy-R-h],[cx-w/2,cy+26],[cx-w/2,cy-26-h],[cx+R,cy-h/2],[cx-R-w,cy-h/2]]],
    [capA,(w,h)=>[[M,M],[M,H-M-hb-6-h],[W-M-w,M]]],
    [capB,(w,h)=>[[M,H-M-h],[W-M-w,H-M-h]]],
    [capD,(w,h)=>[[W-M-w,H-M-h],[W-M-w,M]]]
  ];
  const meets=(c,w,h,set)=>set.some(o=>c[0]<o[2]+5&&o[0]<c[0]+w+5&&c[1]<o[3]+5&&o[1]<c[1]+h+5);
  for(const [el,spots] of list){
    if(el.hidden)continue;
    const w=el.offsetWidth,h=el.offsetHeight,all=spots(w,h).filter(c=>c[0]>=M&&c[1]>=M&&c[0]+w<=W-M&&c[1]+h<=H-M);
    const c=all.find(c=>!meets(c,w,h,fixed)&&!meets(c,w,h,boxes))||all.find(c=>!meets(c,w,h,boxes));
    if(!c){el.hidden=true;if(el===capC)roomC=false;continue;}
    el.style.left=c[0]+'px';el.style.top=c[1]+'px';boxes.push(spot[caps.indexOf(el)]=[c[0],c[1],c[0]+w,c[1]+h]);
  }
  capC.hidden=!(FORCE&&parked&&roomC);
  caps.forEach((el,i)=>{want[i]=!el.hidden;gone[i]=0;});
  dodge();
}
// The followed dots on show, and the end of a dot's drift arrow
const seen=()=>(phoneQ.matches?follow.slice(1,2):follow).filter(Boolean);
function tip(p){const v=Math.hypot(p.vx,p.vy)||1,len=Math.max(v*60,p.r+14);return[p.x+p.vx/v*len,p.y+p.vy/v*len];}
// A caption never covers a followed dot or its arrow: it steps aside while one is near it and comes back once the dot has passed
// (it leaves 8px out from the dot's edge and returns 18px out, so it does not flicker). Runs with each drawn picture, never a search.
function dodge(){
  for(let i=0;i<4;i++){
    const b=spot[i];if(!b||!want[i])continue;
    let hit=false;
    for(const p of seen()){
      const [x1,y1]=tip(p),m=p.r+3+(gone[i]?18:8);
      for(let t=0;t<=3&&!hit;t++){
        const x=p.x+(x1-p.x)*t/3,y=p.y+(y1-p.y)*t/3;
        hit=Math.hypot(Math.max(b[0]-x,0,x-b[2]),Math.max(b[1]-y,0,y-b[3]))<m;
      }
    }
    if(hit!==!!gone[i]){gone[i]=hit?1:0;caps[i].hidden=hit;}
  }
}
function inside(){if(mode==='inside'){place();drawMarks();}}

// Where the dots feel the pointer: the real one; in See inside a pretend one parked where none is over the box; in Compare the real one mapped into its half
function setMouse(){
  const out=raw.x<-900;
  parked=mode==='inside'&&out;
  if(parked){mouse.x=park.x;mouse.y=park.y;}
  else if(mode==='compare'&&!out){mouse.x=raw.x>HW+1?raw.x-HW-2:raw.x;mouse.y=raw.y-TOP;}
  else{mouse.x=raw.x;mouse.y=raw.y;}
  const w=FORCE&&parked&&roomC;if(mode==='inside'&&!!want[2]!==w){want[2]=w?1:0;gone[2]=0;capC.hidden=!w;} // its caption shows only with the cursor
}

// The notes: the markup holds the default words, written again only when a setting or reduced motion changes them. Shown still
// (reduced motion, paused) they use no word of movement over the picture.
const noteIn=document.querySelector('[data-hb-for="inside"]'),noteCmp=document.querySelector('[data-hb-for="compare"]');
const reduced=matchMedia('(prefers-reduced-motion: reduce)');
function notes(){
  label();
  const s=paused&&reduced.matches,c=CONNECTIONS,v=FORCE<0?['push away','pushes away']:['pull in','pulls in'];
  put(noteIn,(s?'Inside, each arrow shows where a dot would drift'+(c?', and a ringed dot joins every dot in its ring. ':'; Link distance is None, so no dot joins another. ')
    :'Inside, each dot drifts its own way'+(c?' and joins every dot inside its dashed ring with a line. ':'; Link distance is None, so no dot joins another. '))
    +(FORCE?`The pointer ${s?'would '+v[0]:v[1]} dots inside its ${s?'':'own '}ring; point at the box to move it.`:'Pointer effect is None, so the pointer moves nothing.'));
  put(noteCmp,c?`Dots only and With links ${s?'show the same dots in the same places':'are the same dots moving the same way'}. Only the lines differ: they join dots that come close, which turns the dots into a network.`
    :'Link distance is None, so Dots only and With links look the same. Pick a distance in Try it to see the lines.');
}
const LABEL={normal:cvs.getAttribute('aria-label'),compare:'The same dots twice: drawn alone, and joined by lines where they come close'};
// The picture's name says what the mode draws: one ringed dot on phones, no rings at Link distance None, no pointer ring at None
function label(){
  const one=phoneQ.matches,t=mode==='normal'?LABEL.normal:mode==='compare'?(CONNECTIONS?LABEL.compare:'The same dots twice, drawn alone in both halves because Link distance is None')
    :'Dots drifting, '+(one?'one':'three')+' of them '+(CONNECTIONS?'ringed to show how near another dot must be to join it, with ':'marked, with ')+(one?'an arrow for its':'arrows for their')+' drift'+(FORCE?' and a ring for the pointer’s reach':'');
  if(cvs.getAttribute('aria-label')!==t)cvs.setAttribute('aria-label',t);
}
// Registered at the top level, before the shared script. Compare keeps Normal's dots and picture and puts them back; See inside works on Normal's own dots.
document.addEventListener('hb:mode',e=>{
  const was=mode,now=e.detail.mode;mode=now;
  if(now==='compare'&&was!=='compare'){
    keep.width=cvs.width;keep.height=cvs.height;kctx.drawImage(cvs,0,0);
    kept={parts:particles,follow,ok:was==='normal'};setWorld();spawn();
  }else if(was==='compare'&&now!=='compare'){
    setWorld();
    if(kept){particles=kept.parts;follow=kept.follow;}else spawn();
  }
  if(now!==was&&(now==='compare'||was==='compare')){
    ctx.clearRect(0,0,W,H);
    if(was==='compare'&&now==='normal'&&kept&&kept.ok){ctx.setTransform(1,0,0,1,0,0);ctx.drawImage(keep,0,0);ctx.setTransform(dpr,0,0,dpr,0,0);}
    else draw();
    if(was==='compare')kept=null;
  }else if(now!==was)redraw();
  setMouse();
  if(now==='inside'){place();drawMarks();}else mctx.clearRect(0,0,W,H);
  notes();
});

resize();spawn();draw();start();

// The pointer is recorded even while paused; the dots react to it only when a frame is drawn.
// A mouse or pen uses pointer events. A finger uses touch events, so it keeps working while the page scrolls;
// its pointer events are skipped because a tap is followed by mouse events that would put the pointer back.
function moved(){setMouse();if(mode==='inside'&&paused)drawMarks();}
function aim(x,y){const r=cvs.getBoundingClientRect();raw.x=x-r.left;raw.y=y-r.top;moved();}
function away(){raw.x=raw.y=-999;moved();}
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(ev=>stage.addEventListener(ev,away));
// A change of the dots' world drops Compare's kept Normal set (made for the old one), which then spawns again on return
function after(){redraw();inside();notes();}
// A phone's address bar showing or hiding changes only the window's height, not the stage's, so nothing is scattered again
window.addEventListener('resize',()=>{
  if(stage.clientWidth===W&&stage.clientHeight===H)return;
  resize();kept=null;spawn();setMouse();after();
});
document.fonts.ready.then(()=>{if(mode==='inside')place();});
reduced.addEventListener('change',notes);

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);
  }));
}
// A setting that changes how Normal looks makes Compare's kept picture old (its kept dots stay good)
choices('force-seg',d=>{FORCE=+d.force;setMouse();inside();notes();});
choices('count-seg',d=>{if(+d.level===level)return;level=+d.level;kept=null;spawn();after();});
choices('link-seg',d=>{CONNECTIONS=d.dist!=='0';if(CONNECTIONS)DIST=+d.dist;if(kept)kept.ok=false;after();});
choices('speed-seg',d=>{
  const n=+d.spd,k=n/SPD;SPD=n;particles.forEach(p=>{p.vx*=k;p.vy*=k;});
  if(kept)kept.parts.forEach(p=>{p.vx*=k;p.vy*=k;});
  if(mode==='inside')drawMarks();
});
choices('color-sw',d=>{COLOR=d.color;if(kept)kept.ok=false;after();});
document.getElementById('trail-tog').addEventListener('change',e=>{TRAILS=e.target.checked;if(kept)kept.ok=false;after();});
</script>
</body>
</html>