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: move Particle Constellation to the guided-steps page

matin5cf0a3f69458
diff --git a/animations/07-ambient-background/particle-constellation/README.md b/animations/07-ambient-background/particle-constellation/README.md
index 4c83057c..a367d2df 100644
--- a/animations/07-ambient-background/particle-constellation/README.md
+++ b/animations/07-ambient-background/particle-constellation/README.md
@@ -1,7 +1,7 @@
# Particle Constellation
## What it is
-A field of small nodes drifts slowly across a canvas, and any two nodes closer than a set distance are joined by a line whose opacity fades as they separate. The result is a shifting network mesh — the "connected dots" hero background seen behind countless product and crypto landing pages.
+A particle constellation is a field of small dots drifting slowly across a background, where any two dots that come close enough are joined by a thin line that fades as they move apart. The lines keep forming and breaking, so the network seems to shift and grow: the "connected dots" background behind many tech and product sites.
## When to use it
- Hero sections for tech, network, security, or data products
@@ -14,38 +14,41 @@ Nodes are plain objects with a position and velocity; they drift and bounce off
```js
const L2 = LINK * LINK;
+ctx.strokeStyle = `rgb(${c[0]},${c[1]},${c[2]})`;
for (let i = 0; i < nodes.length; i++) {
const a = nodes[i];
for (let j = i + 1; j < nodes.length; j++) {
const b = nodes[j], dx = a.x - b.x, dy = a.y - b.y, d2 = dx*dx + dy*dy;
if (d2 < L2) {
- const op = (1 - Math.sqrt(d2) / LINK) * 0.55;
- ctx.strokeStyle = `rgba(${c[0]},${c[1]},${c[2]},${op})`;
+ ctx.globalAlpha = (1 - Math.sqrt(d2) / LINK) * 0.55;
ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke();
}
}
}
+ctx.globalAlpha = 1;
```
-Optional mouse attraction nudges each node's velocity toward the pointer, so the mesh gathers where the cursor rests.
+Every line shares one stroke color and gets its fade from `globalAlpha`; building a new color string for each line costs several times more.
+
+Optional mouse attraction nudges each node's velocity toward the pointer, so the mesh gathers where the cursor rests. Each node remembers the velocity it started with and eases back to it every frame, so a pull from the pointer fades away while the slow drift goes on. On touch screens the pointer's position also comes from `pointerdown`, so a resting finger works too.
## Key parameters
| Parameter | Default | Effect |
|-----------|---------|--------|
-| Node count | 90 | Line tests grow as count², so this dominates cost |
-| Link distance | 130px | Larger = denser web; too large and everything connects to everything |
-| Drift speed | 0.6 | Ambient range is 0.3–1.0; above that it reads as agitated |
-| Mouse attraction | on | Pull strength is capped and damped so it stays gentle |
-| Color | cyan | RGB triple reused for both nodes and lines |
+| Number of dots | Medium | Few is 50, medium 90 and many 140; phones show at most 60, because every pair of dots is checked each frame |
+| Link distance | Medium | How close two dots must be to be linked: short is 90px, medium 130px and long 180px; too long and everything links to everything |
+| Speed | Normal | How fast the dots drift: slow is 0.35, normal 0.6 and fast 1; faster looks agitated |
+| Color | Cyan | The color of the dots and lines: cyan, violet, mint or gray |
+| Dots follow the pointer | on | Dots near the pointer, or a finger, drift toward it and gather there |
## Production notes
-- **The n² wall**: connection testing is O(n²). At ~150 nodes you are doing >11,000 distance checks per frame. This demo caps nodes at 60 on screens under 600px to hold 60fps on mid-range phones. For larger fields, bucket nodes into a spatial grid and only test neighboring cells.
-- **Velocity damping**: multiplying velocity by 0.99 each frame keeps the mouse-attraction impulses from accumulating into runaway speeds — without it, the field slowly boils.
-- **Reduced motion**: the animation loop never starts; a single static frame is drawn and re-rendered only when a control changes, honoring `prefers-reduced-motion`.
+- **The n² wall**: connection testing is O(n²). At ~150 nodes you are doing >11,000 distance checks per frame. This demo caps nodes at 60 on phone-sized screens (up to 600px wide, or up to 500px tall for a phone held sideways) to hold 60fps on mid-range phones. For larger fields, bucket nodes into a spatial grid and only test neighboring cells.
+- **Velocity easing**: each frame, a node's velocity eases 1% of the way back to the velocity it started with. That keeps pulls from the pointer from building into runaway speeds, and unlike multiplying the velocity by 0.99, which slows every node to a stop within seconds, it never lets the drift die out.
+- **Reduced motion**: the demo starts paused, showing one still frame, until the visitor presses Play. In production, show these visitors the still frame.
- **Retina**: for crisp lines on high-DPI screens, scale the canvas backing store by `devicePixelRatio` and the context by the same factor. Omitted here to keep fill rate low on mobile.
- **Library equivalents**: [tsParticles](https://github.com/matteobruni/tsparticles) ships this exact effect (`links` mode) with presets; [three.js](https://threejs.org) can push the same idea to tens of thousands of GPU points with `LineSegments`.
## See also
-- [Starfield](../starfield/) — particles as depth rather than a network
-- [Floating Elements](../floating-elements/) — drifting shapes on independent paths
-- [Grid / Dot Pattern Parallax](../grid-dot-pattern-parallax/) — a static lattice that reacts to the mouse
+- [Starfield / Space Particles](../starfield/) — particles that show depth instead of links
+- [Floating Elements](../floating-elements/) — shapes that drift on their own paths
+- [Grid / Dot Pattern Parallax](../grid-dot-pattern-parallax/) — a still grid that shifts against the pointer
diff --git a/animations/07-ambient-background/particle-constellation/index.html b/animations/07-ambient-background/particle-constellation/index.html
index da495c5b..bd1a44dc 100644
--- a/animations/07-ambient-background/particle-constellation/index.html
+++ b/animations/07-ambient-background/particle-constellation/index.html
@@ -4,7 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Particle Constellation — Animation Handbook</title>
- <meta name="description" content="Drifting nodes link to nearby neighbors — line opacity fades with distance, building a living network mesh.">
+ <meta name="description" content="Drifting dots link up with lines whenever they come close. Best for tech sites.">
<link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/particle-constellation/">
<link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png">
<link rel="icon" type="image/svg+xml" href="../../../favicon.svg">
@@ -12,168 +12,252 @@
<meta property="og:type" content="article">
<meta property="og:site_name" content="Animation Handbook">
<meta property="og:title" content="Particle Constellation — Animation Handbook">
- <meta property="og:description" content="Drifting nodes link to nearby neighbors — line opacity fades with distance, building a living network mesh.">
+ <meta property="og:description" content="Drifting dots link up with lines whenever they come close. Best for tech sites.">
<meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/particle-constellation/">
<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="Particle Constellation — Animation Handbook">
- <meta name="twitter:description" content="Drifting nodes link to nearby neighbors — line opacity fades with distance, building a living network mesh.">
+ <meta name="twitter:description" content="Drifting dots link up with lines whenever they come close. 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": "Particle Constellation", "name": "Particle Constellation", "description": "Drifting nodes link to nearby neighbors — line opacity fades with distance, building a living network mesh.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/particle-constellation/", "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, Particle Constellation"}</script>
+ <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "Particle Constellation", "name": "Particle Constellation", "description": "Drifting dots link up with lines whenever they come close. Best for tech sites.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/particle-constellation/", "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, Particle Constellation"}</script>
<style>
- @font-face{font-family:'Bricolage';src:url('../../../assets/fonts/brico-700.woff2') format('woff2');font-weight:700;font-display:swap}
- @font-face{font-family:'PlexMono';src:url('../../../assets/fonts/plex-400.woff2') format('woff2');font-weight:400;font-display:swap}
- :root{--bg:#0b0b0d;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#5ad1ff;--ui-text:#f4f4f2;--ui-muted:#77777e;--disp:'Bricolage','Arial Narrow',sans-serif;--mono:'PlexMono',ui-monospace,Menlo,Consolas,monospace;--stage-h:620px}
+ :root{--ui-accent:#ffce5a}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
- body{background:var(--bg);color:var(--ui-text);font-family:var(--mono);-webkit-font-smoothing:antialiased;padding:clamp(12px,3vw,24px)}
- header{margin-bottom:20px}
- header h1{font-family:var(--disp);font-weight:700;font-size:clamp(11px,1.8vw,15px);letter-spacing:-.01em}
- header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}
- .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}
- .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;overflow:hidden;position:relative;background:#06070c}
+ .stage{position:relative;overflow:hidden;background:#06070c}
canvas{display:block;width:100%;height:100%}
- .fps-badge{position:absolute;top:8px;right:8px;font-size:9px;color:rgba(255,255,255,.4);background:rgba(0,0,0,.5);padding:3px 8px;border-radius:4px;pointer-events:none}
- aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}
- .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}
- .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}
- .div{height:1px;background:var(--ui-border)}
- .sr{display:flex;align-items:center;gap:6px;font-size:10px}
- .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}
- .sv{width:44px;text-align:right;color:var(--ui-text)}
- select{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:8px 6px;border-radius:4px;width:100%;min-height:44px}
- .tog{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}
- .tog input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}
- button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}
- @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}
- @media(max-width:600px){.layout{flex-direction:column;align-items:stretch}.stage{flex:none;width:100%}aside{width:100%}:root{--stage-h:380px}}
- @media(prefers-reduced-motion:reduce){.fps-badge,#pause-btn{display:none}}
</style>
-<style id="ah-inject">
-:root{--ah-bg:rgba(17,17,20,.82);--ah-line:rgba(255,255,255,.1);--ah-ink:#f4f4f2;--ah-muted:#9a9aa2;--ah-accent:#6ea8ff}
-body{padding-top:46px}
-.ah-bar{position:fixed;top:0;left:0;right:0;height:46px;z-index:2147483000;display:flex;align-items:center;justify-content:space-between;gap:10px;padding:0 clamp(10px,3vw,18px);background:var(--ah-bg);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border-bottom:1px solid var(--ah-line);font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px;box-sizing:border-box}
-.ah-bar a,.ah-bar button{color:var(--ah-muted);text-decoration:none;background:none;border:0;font:inherit;cursor:pointer;display:inline-flex;align-items:center;gap:6px;min-height:34px;padding:0 7px;border-radius:6px;transition:color .18s,background .18s;white-space:nowrap}
-.ah-bar a:hover,.ah-bar button:hover{color:var(--ah-ink)}
-.ah-home{color:var(--ah-ink);font-weight:600}
-.ah-actions{display:flex;align-items:center;gap:2px}
-.ah-sep{width:1px;height:16px;background:var(--ah-line);margin:0 4px}
-.ah-copied{color:var(--ah-accent)!important}
-@media(max-width:600px){.ah-bar .ah-hideSm{display:none}}
-@media print{.ah-bar{display:none}body{padding-top:0}}
-</style>
+ <link rel="stylesheet" href="../../../assets/css/demo-page.css?v=3">
+ <script src="../../../assets/js/demo-page.js?v=3" defer></script>
</head>
-<body>
-<div class="ah-bar" role="navigation" aria-label="Animation Handbook"><a class="ah-home" href="../../../">← Animation Handbook</a><span class="ah-actions"><a class="ah-hideSm" href="../abstract-geometric-motion/" rel="prev" title="Previous">‹ Prev</a><a class="ah-hideSm" href="../flow-field/" rel="next" title="Next">Next ›</a><span class="ah-sep ah-hideSm"></span><button type="button" id="ah-copy" class="ah-hideSm">Copy source</button><a class="ah-hideSm" href="https://github.com/matinmonshizadeh/animation-handbook/blob/main/animations/07-ambient-background/particle-constellation/index.html" target="_blank" rel="noopener noreferrer">Source ↗</a></span></div>
-<header>
- <h1>Particle Constellation</h1>
- <p>Drifting nodes link to nearby neighbors — line opacity fades with distance, building a living network mesh.</p>
-</header>
-<div class="layout">
- <div class="stage" id="stage">
- <canvas id="cvs"></canvas>
- <div class="fps-badge" id="fps">— fps</div>
- </div>
- <aside>
- <p class="note">The whole effect is one rule: for every pair of nodes closer than the link distance, draw a line whose opacity is proportional to how close they are. Nodes never touch — the connections do the work.</p>
- <div class="lbl">Node Count</div>
- <div class="sr"><input type="range" id="count-sl" min="20" max="160" value="90" step="10"><span class="sv" id="count-v">90</span></div>
- <div class="lbl">Link Distance</div>
- <div class="sr"><input type="range" id="link-sl" min="60" max="220" value="130" step="10"><span class="sv" id="link-v">130</span></div>
- <div class="lbl">Drift Speed</div>
- <div class="sr"><input type="range" id="spd-sl" min="1" max="20" value="6" step="1"><span class="sv" id="spd-v">0.6</span></div>
- <div class="lbl">Color</div>
- <select id="col-sel">
- <option value="cyan" selected>Cyan</option>
- <option value="violet">Violet</option>
- <option value="mint">Mint</option>
- <option value="mono">Monochrome</option>
- </select>
- <label class="tog"><input type="checkbox" id="mouse-tog" checked><span>Mouse attraction</span></label>
- <div class="div"></div>
- <div style="font-size:9px;color:var(--ui-muted)">Nodes cap at 60 on small screens for 60fps.</div>
- <button class="rst" id="pause-btn">⏸ Pause</button>
- </aside>
-</div>
-<script>
-const cvs=document.getElementById('cvs'),ctx=cvs.getContext('2d');
-const stage=document.getElementById('stage'),fpsEl=document.getElementById('fps');
-let W,H,paused=false,raf=null,lastT=0;
-let COUNT=90,LINK=130,SPD=0.6,COL='cyan',MOUSE=true;
-let nodes=[],mx=-999,my=-999;
-const PAL={cyan:[90,209,255],violet:[168,130,255],mint:[122,255,200],mono:[220,220,225]};
-const reduce=window.matchMedia('(prefers-reduced-motion:reduce)').matches;
+<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="../abstract-geometric-motion/" rel="prev" aria-label="Previous: Abstract Geometric Motion"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg><span><span class="hb-dir">Previous: </span>Abstract Geometric Motion</span></a><a href="../flow-field/" rel="next" aria-label="Next: Flow Field"><span><span class="hb-dir">Next: </span>Flow Field</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m9 18 6-6-6-6"/></svg></a></span>
+</nav>
+<main class="hb-page">
+ <header class="hb-head">
+ <p class="hb-cat">07.13 · Ambient &amp; Background</p>
+ <h1>Particle Constellation</h1>
+ <p class="hb-lede">Drifting dots link up with lines whenever they come close. 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 gather toward your pointer or finger. Pause it to look closely, or turn on slow motion.</p></div>
+ </div>
+ <div class="stage">
+ <canvas id="cvs" aria-hidden="true"></canvas>
+ </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>
+ </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 dots</p>
+ <div class="seg" id="count-seg" role="group" aria-labelledby="count-lbl">
+ <button type="button" data-n="50" aria-pressed="false">Few</button>
+ <button type="button" data-n="90" class="on" aria-pressed="true">Medium</button>
+ <button type="button" data-n="140" aria-pressed="false">Many</button>
+ </div>
+ <p class="hb-hint">More dots, more links; phones show at most 60.</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-px="90" aria-pressed="false">Short</button>
+ <button type="button" data-px="130" class="on" aria-pressed="true">Medium</button>
+ <button type="button" data-px="180" aria-pressed="false">Long</button>
+ </div>
+ <p class="hb-hint">How close two dots must be to link up.</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.35" aria-pressed="false">Slow</button>
+ <button type="button" data-spd="0.6" class="on" aria-pressed="true">Normal</button>
+ <button type="button" data-spd="1" aria-pressed="false">Fast</button>
+ </div>
+ <p class="hb-hint">Slow drifting stays calm.</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="color-lbl">Color</p>
+ <div class="swatches" id="color-sw" role="group" aria-labelledby="color-lbl">
+ <button type="button" class="on" aria-pressed="true" aria-label="Cyan" data-col="cyan" style="background:#5ad1ff"></button>
+ <button type="button" aria-pressed="false" aria-label="Violet" data-col="violet" style="background:#a882ff"></button>
+ <button type="button" aria-pressed="false" aria-label="Mint" data-col="mint" style="background:#7affc8"></button>
+ <button type="button" aria-pressed="false" aria-label="Gray" data-col="mono" style="background:#dcdce1"></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>Dots follow the pointer</span><input class="hb-switch" type="checkbox" role="switch" id="mouse-tog" checked autocomplete="off"></label>
+ <p class="hb-hint">Dots gather where you point or touch.</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 constellation background to [the section you want it behind]. Scatter dots on a canvas, let each drift slowly in its own direction and bounce off the edges, and on every frame join any two dots that are close with a thin line that fades as they move apart, so a network keeps forming and breaking. When the settings include it, let the dots drift toward the pointer, or toward a finger on touch screens. Checking every pair of dots gets slow fast, so use fewer dots on phones. If the visitor has reduced motion turned on, show one still frame. 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>
+ </section>
-function effCount(){return W<600?Math.min(COUNT,60):COUNT;}
-function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;init();if(reduce||paused)draw();}
+ <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>Tech and data sites</li><li>Hero sections</li><li>Network and security products</li><li>Loading screens</li></ul>
+ <h3>Avoid on</h3>
+ <ul class="hb-tags hb-avoid"><li>Busy layouts</li><li>Long reading pages</li></ul>
+ </div>
+ </section>
-function init(){
- const n=effCount();
- nodes=Array.from({length:n},()=>({
- x:Math.random()*W,y:Math.random()*H,
- vx:(Math.random()-.5),vy:(Math.random()-.5),
- r:Math.random()*1.4+1
- }));
-}
+ <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="#top">Back to top ↑</a></footer>
+<script>
+ const cvs=document.getElementById('cvs'),ctx=cvs.getContext('2d');
+ const stage=document.querySelector('.stage');
+ const slowTog=document.getElementById('slow-tog');
+ const PAL={cyan:[90,209,255],violet:[168,130,255],mint:[122,255,200],mono:[220,220,225]};
+ const PHONE_DOTS=60; // phones and short screens draw at most this many dots: every pair is tested each frame
+ const phone=matchMedia('(max-width:600px),(max-height:500px)');
+ let W=0,H=0,raf=null,lastT=0,paused=false;
+ let COUNT=90,LINK=130,SPD=0.6,COL='cyan',MOUSE=true;
+ let nodes=[],mx=-999,my=-999;
+
+ function init(){
+ const n=phone.matches?Math.min(COUNT,PHONE_DOTS):COUNT;
+ nodes=Array.from({length:n},()=>{
+ const vx=Math.random()-.5,vy=Math.random()-.5;
+ // cvx and cvy are the velocity the dot cruises at and eases back to, so the drift never dies
+ return{x:Math.random()*W,y:Math.random()*H,vx,vy,cvx:vx,cvy:vy,r:Math.random()*1.4+1};
+ });
+ }
-function step(){
- for(const p of nodes){
- p.x+=p.vx*SPD;p.y+=p.vy*SPD;
- if(MOUSE&&mx>-500){
- const dx=mx-p.x,dy=my-p.y,d2=dx*dx+dy*dy;
- if(d2<26000&&d2>1){const f=.04/Math.sqrt(d2);p.vx+=dx*f;p.vy+=dy*f;}
+ // k is 1, or a third in slow motion: the drift, the pull toward the pointer and the easing all shrink by it
+ function step(k){
+ for(const p of nodes){
+ p.x+=p.vx*SPD*k;p.y+=p.vy*SPD*k;
+ if(MOUSE&&mx>-500){
+ const dx=mx-p.x,dy=my-p.y,d2=dx*dx+dy*dy;
+ if(d2<26000&&d2>1){const f=.04/Math.sqrt(d2)*k;p.vx+=dx*f;p.vy+=dy*f;}
+ }
+ p.vx+=(p.cvx-p.vx)*.01*k;p.vy+=(p.cvy-p.vy)*.01*k;
+ // a bounce points the velocity and the cruising velocity away from the wall, so a dot pulled against it cannot turn back in
+ if(p.x<0){p.vx=Math.abs(p.vx);p.cvx=Math.abs(p.cvx);}else if(p.x>W){p.vx=-Math.abs(p.vx);p.cvx=-Math.abs(p.cvx);}
+ if(p.y<0){p.vy=Math.abs(p.vy);p.cvy=Math.abs(p.cvy);}else if(p.y>H){p.vy=-Math.abs(p.vy);p.cvy=-Math.abs(p.cvy);}
+ p.x=Math.max(0,Math.min(W,p.x));p.y=Math.max(0,Math.min(H,p.y));
}
- // gentle damping keeps velocities bounded so drift stays ambient
- p.vx*=.99;p.vy*=.99;
- if(p.x<0||p.x>W)p.vx*=-1;if(p.y<0||p.y>H)p.vy*=-1;
- p.x=Math.max(0,Math.min(W,p.x));p.y=Math.max(0,Math.min(H,p.y));
}
-}
-function draw(){
- ctx.clearRect(0,0,W,H);
- const c=PAL[COL],L2=LINK*LINK;
- for(let i=0;i<nodes.length;i++){
- const a=nodes[i];
- for(let j=i+1;j<nodes.length;j++){
- const b=nodes[j],dx=a.x-b.x,dy=a.y-b.y,d2=dx*dx+dy*dy;
- if(d2<L2){
- const op=(1-Math.sqrt(d2)/LINK)*.55;
- ctx.strokeStyle=`rgba(${c[0]},${c[1]},${c[2]},${op})`;
- ctx.lineWidth=1;
- ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.stroke();
+ // The whole picture for where the dots are; the canvas is cleared first, so no trace of an earlier picture stays.
+ // Every link has the same color and is faded with globalAlpha: a new color string for each link costs several times more.
+ function draw(){
+ ctx.clearRect(0,0,W,H);
+ const c=PAL[COL],L2=LINK*LINK;
+ ctx.strokeStyle=`rgb(${c[0]},${c[1]},${c[2]})`;ctx.lineWidth=1;
+ for(let i=0;i<nodes.length;i++){
+ const a=nodes[i];
+ for(let j=i+1;j<nodes.length;j++){
+ const b=nodes[j],dx=a.x-b.x,dy=a.y-b.y,d2=dx*dx+dy*dy;
+ if(d2<L2){
+ ctx.globalAlpha=(1-Math.sqrt(d2)/LINK)*.55;
+ ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.stroke();
+ }
}
}
+ ctx.globalAlpha=1;
+ ctx.fillStyle=`rgba(${c[0]},${c[1]},${c[2]},.9)`;
+ for(const p of nodes){ctx.beginPath();ctx.arc(p.x,p.y,p.r,0,Math.PI*2);ctx.fill();}
+ }
+
+ // loop() keeps exactly one frame requested in raf; Pause cancels it and Play starts one loop again. At most one picture per 16 ms.
+ function loop(ts){
+ raf=requestAnimationFrame(loop);
+ if(ts-lastT<16)return;
+ lastT=ts;
+ step(slowTog.checked?1/3:1);draw();
}
- ctx.fillStyle=`rgba(${c[0]},${c[1]},${c[2]},.9)`;
- for(const p of nodes){ctx.beginPath();ctx.arc(p.x,p.y,p.r,0,Math.PI*2);ctx.fill();}
-}
+ function start(){if(raf)return;lastT=0;raf=requestAnimationFrame(loop);}
-function loop(ts){
- if(paused){raf=null;return;}
- raf=requestAnimationFrame(loop);
- const dt=ts-lastT;if(dt<16)return;lastT=ts;
- fpsEl.textContent=Math.round(1000/(dt||16))+' fps';
- step();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. The dots on screen stay where they are while paused.
+ document.addEventListener('hb:pause',e=>{
+ paused=e.detail.paused;
+ if(paused){cancelAnimationFrame(raf);raf=null;}
+ else start();
+ });
-resize();
-if(reduce){step();draw();fpsEl.textContent='static';}
-else raf=requestAnimationFrame(loop);
-window.addEventListener('resize',resize);
+ // Setting the canvas size wipes it, so a real change of the stage's size scatters the dots and draws them at once,
+ // playing or paused. 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;
+ W=cvs.width=w;H=cvs.height=h;
+ init();draw();
+ }
+
+ // The pointer's position comes from pointermove and pointerdown, so a finger resting on the stage draws the dots too
+ function aim(e){if(!e.isPrimary)return;const r=stage.getBoundingClientRect();mx=e.clientX-r.left;my=e.clientY-r.top;}
+ function away(e){if(e.isPrimary)mx=my=-999;}
+ stage.addEventListener('pointermove',aim);
+ stage.addEventListener('pointerdown',aim);
+ stage.addEventListener('pointerleave',away);
+ stage.addEventListener('pointercancel',away);
-stage.addEventListener('pointermove',e=>{const r=stage.getBoundingClientRect();mx=e.clientX-r.left;my=e.clientY-r.top;});
-stage.addEventListener('pointerleave',()=>{mx=my=-999;});
+ 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);
+ }));
+ }
+ // A setting that changes the picture draws it at once, so the change shows while the loop is paused (or is paused a
+ // moment later, before the next frame). Speed and the pointer switch change no picture: the dots carry on from where they are.
+ choices('count-seg',d=>{COUNT=+d.n;init();draw();});
+ choices('link-seg',d=>{LINK=+d.px;draw();});
+ choices('speed-seg',d=>{SPD=+d.spd;});
+ choices('color-sw',d=>{COL=d.col;draw();});
+ document.getElementById('mouse-tog').addEventListener('change',e=>{MOUSE=e.target.checked;});
-document.getElementById('count-sl').addEventListener('input',e=>{COUNT=+e.target.value;document.getElementById('count-v').textContent=COUNT;init();if(reduce){draw();}});
-document.getElementById('link-sl').addEventListener('input',e=>{LINK=+e.target.value;document.getElementById('link-v').textContent=LINK;if(reduce){draw();}});
-document.getElementById('spd-sl').addEventListener('input',e=>{SPD=e.target.value/10;document.getElementById('spd-v').textContent=SPD.toFixed(1);});
-document.getElementById('col-sel').addEventListener('change',e=>{COL=e.target.value;if(reduce){draw();}});
-document.getElementById('mouse-tog').addEventListener('change',e=>{MOUSE=e.target.checked;});
-document.getElementById('pause-btn').addEventListener('click',()=>{
- paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';
- if(!paused&&!reduce){lastT=performance.now();raf=requestAnimationFrame(loop);}
-});
+ resize();
+ window.addEventListener('resize',resize);
+ start();
+ phone.addEventListener('change',()=>{init();draw();}); // a window that crosses the phone size changes how many dots it shows
</script>
-<script>(function(){var b=document.getElementById("ah-copy");if(!b)return;b.addEventListener("click",function(){fetch(location.href).then(function(r){return r.text();}).catch(function(){return document.documentElement.outerHTML;}).then(function(t){return navigator.clipboard.writeText(t);}).then(function(){b.textContent="Copied!";b.classList.add("ah-copied");setTimeout(function(){b.textContent="Copy source";b.classList.remove("ah-copied");},1500);}).catch(function(){b.textContent="Copy failed";setTimeout(function(){b.textContent="Copy source";},1500);});});})();</script>
</body>
</html>
diff --git a/index.html b/index.html
index 1b874e4d..3f5a7090 100644
--- a/index.html
+++ b/index.html
@@ -1045,7 +1045,7 @@ const CATS=[
['floating-elements','Floating Elements','Small shapes drift slowly, each on its own path. Best for hero backgrounds.'],
['grid-dot-pattern-parallax','Grid / Dot Pattern Parallax','A dot grid shifts gently against your pointer for depth. Best for tech sites.'],
['abstract-geometric-motion','Abstract Geometric Motion','Shapes turn, spread and flow in a calm, endless pattern. Best for music players.'],
- ['particle-constellation','Particle Constellation','Drifting nodes link with lines when they come close — the network-mesh hero background.'],
+ ['particle-constellation','Particle Constellation','Drifting dots link up with lines whenever they come close. Best for tech sites.'],
['flow-field','Flow Field','Particles follow a noise-driven vector field, leaving flowing trails.'],
['synthwave-grid','Synthwave Grid','A perspective grid scrolls toward a glowing sun — the retro synthwave horizon.'],
['matrix-rain','Matrix Rain','Columns of glowing characters fall down a dark canvas, leaders bright and trails fading.'],