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 GPGPU Particle System to the guided-steps page

matin02fb77525972
diff --git a/animations/06-3d-advanced/gpgpu-particle-system/README.md b/animations/06-3d-advanced/gpgpu-particle-system/README.md
index 93f71b8f..06de6f85 100644
--- a/animations/06-3d-advanced/gpgpu-particle-system/README.md
+++ b/animations/06-3d-advanced/gpgpu-particle-system/README.md
@@ -1,7 +1,7 @@
# GPGPU Particle System
## What it is
-GPGPU (General-Purpose GPU) particle systems store particle state — position, velocity, age — in floating-point textures rather than JavaScript arrays, and update that state in fragment shaders rather than CPU loops. Each frame, a "physics pass" reads the position texture, computes new positions via a fragment shader, and writes to a second texture. The "render pass" reads the updated positions from a vertex shader and draws each particle as a point. This architecture enables 100,000+ particles at 60fps — impossible with CPU-computed JavaScript arrays.
+A GPU particle system moves tens of thousands of particles on the graphics chip instead of in JavaScript. Every particle's position and speed is stored as one pixel of a texture, and a shader reads last frame's texture and writes the next one, all at once. A second step draws each particle as a tiny point.
## When to use it
- Large-scale particle effects: galaxy simulations, fluid flow, fire systems, crowd simulations
@@ -20,6 +20,7 @@ precision highp float;
uniform sampler2D uPos; // read previous frame's positions
uniform float uTime, uSpeed;
uniform int uBehavior;
+uniform float uStep; // 1, or 1/3 in slow motion
out vec4 outColor; // write new positions
float hash(float n) { return fract(sin(n) * 43758.5); }
@@ -32,13 +33,13 @@ void main() {
// Apply behavior (flow field, vortex, attractor, etc.)
if (uBehavior == 1) { // vortex
float len = length(vec2(x, y)) + 0.01;
- vx += (-y / len) * uSpeed * 0.0004;
- vy += ( x / len) * uSpeed * 0.0004;
- vx -= x * 0.0005; // inward pull to prevent escape
- vy -= y * 0.0005;
+ vx += (-y / len) * uSpeed * 0.0004 * uStep;
+ vy += ( x / len) * uSpeed * 0.0004 * uStep;
+ vx -= x * 0.0005 * uStep; // inward pull to prevent escape
+ vy -= y * 0.0005 * uStep;
}
- vx *= 0.985; vy *= 0.985; // damping
- x += vx; y += vy;
+ vx *= pow(0.985, uStep); vy *= pow(0.985, uStep); // damping
+ x += vx * uStep; y += vy * uStep;
// Respawn anything that leaves clip space
if (abs(x) > 1.0 || abs(y) > 1.0) {
float n = float(coord.x) * 0.0713 + float(coord.y) * 0.1319 + uTime * 0.977;
@@ -81,13 +82,13 @@ void main() {
```
## Key parameters
-| Parameter | Typical value | Effect |
-|-----------|--------------|--------|
-| Texture size | 256×256 | 65k particles. 320×320 = 102k — test FPS before shipping |
-| Physics damping | 0.985 | Higher = more inertia, slower energy loss |
-| Step scale | 0.0002–0.001 | Overall particle speed per frame |
-| Boundary mode | Respawn at ±1.0 | Wrap keeps particle count constant but only survives a divergence-free field |
-| Respawn radius | 0.05–0.95 | Where recycled particles re-enter; a disc keeps the centre fed |
+| Parameter | Default | Effect |
+|-----------|---------|--------|
+| Movement | Flow | Flow follows a shifting field of currents; Swirl circles the middle; Attract pulls everything toward the middle; Orbit sweeps the particles round in rings |
+| Number of particles | 65,000 | 16,000, 65,000 or 100,000 particles, one pixel each of a texture 128, 256 or 320 pixels square; phones start with 16,000 |
+| Speed | Normal | How hard the rule pushes each frame: slow is 0.35, normal 0.6 and fast 1 |
+| Color | One color | One blue, a color from each particle's speed, or colors that slowly shift |
+| Trails | off | Fades the last picture instead of clearing it, so each particle leaves a streak |
## Production notes
- **WebGL2 required**: `RGBA32F` float framebuffer targets require WebGL2 (or the `WEBGL_color_buffer_float` extension in WebGL1, which is less reliably available). WebGL2 is supported in all modern browsers (Chrome 56+, Firefox 51+, Safari 15+).
@@ -100,6 +101,6 @@ void main() {
- **Memory**: 256×256 × 4 channels × 4 bytes (float32) = 1MB per texture. Two textures = 2MB — trivial. At 512×512 (262k particles): 4MB × 2 = 8MB.
## See also
-- [Canvas Particle Effect](../canvas-particle-effect/) — CPU-based, simpler setup for <500 particles
-- [Fluid Simulation](../fluid-simulation/) — SDF-based shader effect with organic merging
-- [WebGL Shader Animation](../webgl-shader-animation/) — same WebGL2 context, different shader focus
+- [Canvas Particle Effect](../canvas-particle-effect/) — hundreds of particles moved in JavaScript
+- [Fluid / Liquid Simulation](../fluid-simulation/) — a shader that melts blobs together
+- [WebGL Shader Animation](../webgl-shader-animation/) — shaders that paint every pixel
diff --git a/animations/06-3d-advanced/gpgpu-particle-system/index.html b/animations/06-3d-advanced/gpgpu-particle-system/index.html
index b8bcceae..fc4413a2 100644
--- a/animations/06-3d-advanced/gpgpu-particle-system/index.html
+++ b/animations/06-3d-advanced/gpgpu-particle-system/index.html
@@ -4,7 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GPGPU Particle System — Animation Handbook</title>
- <meta name="description" content="65k+ particle positions stored in a texture — physics computed by a fragment shader each frame (texture ping-pong).">
+ <meta name="description" content="Tens of thousands of particles flow on the graphics chip. Best for hero effects.">
<link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/gpgpu-particle-system/">
<link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png">
<link rel="icon" type="image/svg+xml" href="../../../favicon.svg">
@@ -12,107 +12,143 @@
<meta property="og:type" content="article">
<meta property="og:site_name" content="Animation Handbook">
<meta property="og:title" content="GPGPU Particle System — Animation Handbook">
- <meta property="og:description" content="65k+ particle positions stored in a texture — physics computed by a fragment shader each frame (texture ping-pong).">
+ <meta property="og:description" content="Tens of thousands of particles flow on the graphics chip. Best for hero effects.">
<meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/gpgpu-particle-system/">
<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="GPGPU Particle System — Animation Handbook">
- <meta name="twitter:description" content="65k+ particle positions stored in a texture — physics computed by a fragment shader each frame (texture ping-pong).">
+ <meta name="twitter:description" content="Tens of thousands of particles flow on the graphics chip. Best for hero effects.">
<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": "GPGPU Particle System", "name": "GPGPU Particle System", "description": "65k+ particle positions stored in a texture — physics computed by a fragment shader each frame (texture ping-pong).", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/gpgpu-particle-system/", "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, GPGPU Particle System"}</script>
+ <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "GPGPU Particle System", "name": "GPGPU Particle System", "description": "Tens of thousands of particles flow on the graphics chip. Best for hero effects.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/gpgpu-particle-system/", "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, GPGPU Particle System"}</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:'Bricolage';src:url('../../../assets/fonts/brico-800.woff2') format('woff2');font-weight:800;font-display:swap}
- @font-face{font-family:'PlexMono';src:url('../../../assets/fonts/plex-400.woff2') format('woff2');font-weight:400;font-display:swap}
- @font-face{font-family:'PlexMono';src:url('../../../assets/fonts/plex-500.woff2') format('woff2');font-weight:500;font-display:swap}
- :root{--bg:#0b0b0d;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#3fd6c4;--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:#3fd6c4}
*,*::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}
+ .stage{position:relative;background:#060a10}
canvas{display:block;width:100%;height:100%}
- .hud{position:absolute;top:8px;left:8px;right:8px;display:flex;justify-content:space-between;pointer-events:none;flex-wrap:wrap;gap:4px}
- .badge{font-size:9px;color:rgba(255,255,255,.5);background:rgba(0,0,0,.4);padding:3px 8px;border-radius:4px}
- .no-wgl2{position:absolute;inset:0;background:var(--bg);display:none;align-items:center;justify-content:center;color:var(--ui-muted);font-size:12px;text-align:center;padding:24px}
- 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)}
- .kv{display:flex;justify-content:space-between;font-size:10px;color:var(--ui-muted)}
- .kv .v{color:var(--ui-text)}
- .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:40px;text-align:right;color:var(--ui-text)}
- select{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:var(--mono);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:var(--mono);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}.stage{flex:none;width:100%}aside{width:100%}:root{--stage-h:380px}}
+ .no-wgl2{position:absolute;inset:0;display:none;align-items:center;justify-content:center;padding:clamp(16px,4vw,32px);background:#060a10;font-size:13px;line-height:1.7;text-align:center;color:rgba(255,255,255,.72);white-space:pre-wrap;overflow-y:auto}
</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="../ray-marching-sdf/" rel="prev" title="Previous">‹ Prev</a><a class="ah-hideSm" href="../image-distortion-hover/" 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/06-3d-advanced/gpgpu-particle-system/index.html" target="_blank" rel="noopener noreferrer">Source ↗</a></span></div>
-<header>
- <h1>GPGPU Particle System</h1>
- <p>65k+ particle positions stored in a texture — physics computed by a fragment shader each frame (texture ping-pong).</p>
-</header>
-<div class="layout">
- <div class="stage" id="stage">
- <canvas id="cvs"></canvas>
- <div class="hud">
- <div class="badge" id="fps">— fps</div>
- <div class="badge" id="count-badge">65536 particles</div>
- <div class="badge" id="behavior-badge">Flow Field</div>
+<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="../ray-marching-sdf/" rel="prev" aria-label="Previous: Ray Marching / SDF Scene"><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>Ray Marching / SDF Scene</span></a><a href="../image-distortion-hover/" rel="next" aria-label="Next: Image Distortion on Hover"><span><span class="hb-dir">Next: </span>Image Distortion on Hover</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">06.13 · 3D &amp; Advanced</p>
+ <h1>GPGPU Particle System</h1>
+ <p class="hb-lede">Tens of thousands of particles flow on the graphics chip. Best for hero effects.</p>
+ </header>
+
+ <section class="hb-step hb-watch" aria-labelledby="hb-watch-title">
+ <div class="hb-step-head">
+ <span class="hb-num" aria-hidden="true">1</span>
+ <div><h2 id="hb-watch-title">Watch it</h2><p>It moves by itself. Pause it to look closely, or turn on slow motion to see each part of the movement.</p></div>
+ </div>
+ <div class="stage" id="stage">
+ <canvas id="cvs" role="img" aria-label="Tens of thousands of glowing points flowing across a dark background"></canvas>
+ <div class="no-wgl2" id="no-wgl2"></div>
+ </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="move-lbl">Movement</p>
+ <div class="seg" id="move-seg" role="group" aria-labelledby="move-lbl">
+ <button type="button" data-behavior="0" class="on" aria-pressed="true">Flow</button>
+ <button type="button" data-behavior="1" aria-pressed="false">Swirl</button>
+ <button type="button" data-behavior="2" aria-pressed="false">Attract</button>
+ <button type="button" data-behavior="3" aria-pressed="false">Orbit</button>
+ </div>
+ <p class="hb-hint">The rule every particle follows.</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-n="128" aria-pressed="false">16,000</button>
+ <button type="button" data-n="256" class="on" aria-pressed="true">65,000</button>
+ <button type="button" data-n="320" aria-pressed="false">100,000</button>
+ </div>
+ <p class="hb-hint">Phones start with 16,000; more can be slow there.</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">How hard the rule pushes the particles.</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="seg" id="color-seg" role="group" aria-labelledby="color-lbl">
+ <button type="button" data-mode="0" class="on" aria-pressed="true">One color</button>
+ <button type="button" data-mode="1" aria-pressed="false">By speed</button>
+ <button type="button" data-mode="2" aria-pressed="false">Shifting</button>
+ </div>
+ <p class="hb-hint">One color, by speed, or slowly shifting colors.</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 particle leaves a fading streak.</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 GPU particle system to [the section you want it in]. Keep every particle's position and speed in a floating-point texture, one pixel per particle, and move them all at once in a shader that reads last frame's texture and writes the next, swapping the two each frame. Then draw each particle as a tiny point, following a flowing field, a swirl, a pull to the middle or an orbit. That keeps tens of thousands of particles smooth. Start with far fewer on phones, and show a clear message where WebGL 2 is missing. 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>
+
+ <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="no-wgl2" id="no-wgl2">WebGL2 required for GPGPU texture ping-pong.<br>Try Chrome, Firefox, or Safari 15+.</div>
- </div>
- <aside>
- <p class="note">GPGPU = compute on GPU. Particle data lives in textures — each RGBA32F pixel is one particle's (x, y, vx, vy). A physics shader writes new positions every frame without touching the CPU.</p>
- <div class="lbl">Particle Count</div>
- <select id="count-sel">
- <option value="128">16 384 (16k)</option>
- <option value="256" selected>65 536 (64k)</option>
- <option value="320">102 400 (100k) ⚠</option>
- </select>
- <div class="lbl">Behavior</div>
- <select id="behav-sel">
- <option value="0" selected>Flow Field</option>
- <option value="1">Vortex</option>
- <option value="2">Attractor</option>
- <option value="3">Explosion / Orbit</option>
- </select>
- <div class="lbl">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 Mode</div>
- <select id="col-sel">
- <option value="0" selected>Solid accent</option>
- <option value="1">By velocity</option>
- <option value="2">By age</option>
- </select>
- <label class="tog"><input type="checkbox" id="trail-tog"><span>Motion trails</span></label>
- <div class="div"></div>
- <div class="kv"><span>Texture size</span><span class="v" id="tex-size">256 × 256</span></div>
- <div class="kv"><span>Physics pass</span><span class="v">1 fragment shader</span></div>
- <button class="rst" id="pause-btn">⏸ Pause</button>
- </aside>
-</div>
+ <div class="hb-fit">
+ <h2>Good for</h2>
+ <ul class="hb-tags hb-good"><li>Hero effects</li><li>Data art</li><li>Launch pages</li></ul>
+ <h3>Avoid on</h3>
+ <ul class="hb-tags hb-avoid"><li>Behind text</li><li>Low-power devices</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="#top">Back to top ↑</a></footer>
<script>
// Physics shader (WebGL2 GLSL ES 3.00)
const PHYSICS_VS=`#version 300 es
@@ -120,7 +156,7 @@ in vec2 a;void main(){gl_Position=vec4(a,0.,1.);}`;
const PHYSICS_FS=`#version 300 es
precision highp float;
-uniform sampler2D uPos;uniform float uT,uSpd;uniform int uBehavior;
+uniform sampler2D uPos;uniform float uT,uSpd,uStep;uniform int uBehavior;
out vec4 outCol;
float hash(float n){return fract(sin(n)*43758.5);}
void main(){
@@ -129,23 +165,24 @@ void main(){
float x=p.x,y=p.y,vx=p.z,vy=p.w;
float age=fract(p.w*0.01+uT*0.001); // reuse w channel for age
float spd=uSpd*.0002;
+ // uStep is 1, or 1/3 in slow motion: every change of velocity and every move is scaled by it
if(uBehavior==0){// flow field
float angle=sin(x*2.+uT*.3)*cos(y*2.+uT*.2)+atan(y,x)*.5;
- vx+=cos(angle)*spd;vy+=sin(angle)*spd;
+ vx+=cos(angle)*spd*uStep;vy+=sin(angle)*spd*uStep;
}else if(uBehavior==1){// vortex
float len=length(vec2(x,y))+.01;
- vx+=(-y/len)*spd*2.;vy+=(x/len)*spd*2.;
- vx-=x*.0005;vy-=y*.0005;// inward pull
+ vx+=(-y/len)*spd*2.*uStep;vy+=(x/len)*spd*2.*uStep;
+ vx-=x*.0005*uStep;vy-=y*.0005*uStep;// inward pull
}else if(uBehavior==2){// attractor
vec2 to=-normalize(vec2(x,y));
float d=length(vec2(x,y));
- vx+=to.x*spd*3./(d+.1);vy+=to.y*spd*3./(d+.1);
+ vx+=to.x*spd*3./(d+.1)*uStep;vy+=to.y*spd*3./(d+.1)*uStep;
}else{// orbit with explosion
float ang=atan(y,x)+uT*.2;float r=length(vec2(x,y));
- vx+=cos(ang)*spd-.003*x;vy+=sin(ang)*spd-.003*y;
+ vx+=(cos(ang)*spd-.003*x)*uStep;vy+=(sin(ang)*spd-.003*y)*uStep;
}
- vx*=.985;vy*=.985;// damping
- x+=vx;y+=vy;
+ vx*=pow(.985,uStep);vy*=pow(.985,uStep);// damping
+ x+=vx*uStep;y+=vy*uStep;
// The flow field is divergent, so anything that leaves clip space is respawned
// near the middle. Wrapping instead just stacks every particle on one edge.
if(abs(x)>1.||abs(y)>1.){
@@ -183,18 +220,22 @@ const FADE_FS=`#version 300 es
precision mediump float;out vec4 fragColor;
void main(){fragColor=vec4(.024,.039,.063,.12);}`;
-const stage=document.getElementById('stage'),cvs=document.getElementById('cvs');
-const fpsEl=document.getElementById('fps'),countBadge=document.getElementById('count-badge');
-const behavBadge=document.getElementById('behavior-badge'),texSizeEl=document.getElementById('tex-size');
-const noWgl2=document.getElementById('no-wgl2');
-const BEHAV_NAMES=['Flow Field','Vortex','Attractor','Orbit'];
-const NO_WGL2_MSG=noWgl2.innerHTML;
-// Small screens get the 16k texture by default — 65k points is too much fill for a phone
-const SMALL=matchMedia('(max-width:600px)').matches;
-let W,H,gl,physicsProg,renderProg,fadeProg,qBuf,fbo0,fbo1,tex0,tex1,raf=null;
-let paused=false,lastT=0,startT=0,TEX_N=SMALL?128:256,BEHAVIOR=0,SPD=0.6,COLOR_MODE=0,TRAILS=false;
+const stage=document.getElementById('stage'),cvs=document.getElementById('cvs'),noWgl2=document.getElementById('no-wgl2');
+const slowTog=document.getElementById('slow-tog');
+const NO_WGL2_MSG='This demo needs WebGL 2, which this browser does not offer. Try a recent Chrome, Firefox or Safari.';
+// Phones are screens up to 600px wide, or up to 500px tall when held sideways. They start with the 16k texture:
+// 65k points is too much fill for a phone, and the visitor can still pick more.
+const PHONE=matchMedia('(max-width:600px),(max-height:500px)');
+let W=0,H=0,DPR=1,gl,physicsProg,renderProg,fadeProg,qBuf,fbo0,fbo1,tex0,tex1,raf=null;
+let paused=false,last=null,simT=0,TEX_N=PHONE.matches?128:256,BEHAVIOR=0,SPD=0.6,COLOR_MODE=0,TRAILS=false;
let idxBuf=null,particleCount=0,PT=1.5,shaderErr='';
+// The pressed count follows the start (this runs before the shared script reads the settings for "Your settings")
+document.querySelectorAll('#count-seg button').forEach(b=>{
+ const on=+b.dataset.n===TEX_N;
+ b.classList.toggle('on',on);b.setAttribute('aria-pressed',String(on));
+});
+
function mk(t,s){const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);if(!gl.getShaderParameter(x,gl.COMPILE_STATUS)){shaderErr=gl.getShaderInfoLog(x);console.error(shaderErr);}return x;}
function mkProg(vs,fs){const p=gl.createProgram();gl.attachShader(p,mk(gl.VERTEX_SHADER,vs));gl.attachShader(p,mk(gl.FRAGMENT_SHADER,fs));gl.linkProgram(p);if(!gl.getProgramParameter(p,gl.LINK_STATUS)){shaderErr=gl.getProgramInfoLog(p);console.error(shaderErr);}return p;}
@@ -224,21 +265,22 @@ function initTex(n){
if(idxBuf)gl.deleteBuffer(idxBuf);
idxBuf=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,idxBuf);
gl.bufferData(gl.ARRAY_BUFFER,idx,gl.STATIC_DRAW);
- countBadge.textContent=particleCount.toLocaleString()+' particles';
- texSizeEl.textContent=n+' × '+n;
}
+// The message covers the stage. A canvas that can never draw is also taken out of the page for screen readers.
+function fail(msg){gl=null;cvs.hidden=true;noWgl2.textContent=msg;noWgl2.style.display='flex';}
+
function init(){
// preserveDrawingBuffer keeps last frame for trails; alpha:false avoids premultiplied-alpha artifacts
gl=cvs.getContext('webgl2',{preserveDrawingBuffer:true,alpha:false});
// Rendering into RGBA32F framebuffers requires EXT_color_buffer_float in WebGL2
- if(!gl||!gl.getExtension('EXT_color_buffer_float')){noWgl2.innerHTML=NO_WGL2_MSG;noWgl2.style.display='flex';return false;}
+ if(!gl||!gl.getExtension('EXT_color_buffer_float')){fail(NO_WGL2_MSG);return false;}
shaderErr='';
physicsProg=mkProg(PHYSICS_VS,PHYSICS_FS);
renderProg=mkProg(RENDER_VS,RENDER_FS);
fadeProg=mkProg(PHYSICS_VS,FADE_FS);
// A failed compile otherwise shows as a silent black canvas — say so instead
- if(shaderErr){noWgl2.textContent='Shader failed to build: '+shaderErr;noWgl2.style.display='flex';return false;}
+ if(shaderErr){fail('Shader failed to build: '+shaderErr);return false;}
// Full-screen quad shared by the physics pass and the trail fade
qBuf=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,qBuf);
gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),gl.STATIC_DRAW);
@@ -246,26 +288,30 @@ function init(){
return true;
}
-// Backing store follows devicePixelRatio (capped at 2) so points stay crisp, not upscaled
+// Backing store follows devicePixelRatio (capped at 2) so points stay crisp, not upscaled. Setting the size clears the
+// canvas, so nothing is touched when the stage is the same size (a phone's address bar showing or hiding also fires resize).
+// Says whether the canvas changed.
function resize(){
const dpr=Math.min(window.devicePixelRatio||1,2);
- W=cvs.width=Math.max(1,Math.round(stage.clientWidth*dpr));
- H=cvs.height=Math.max(1,Math.round(stage.clientHeight*dpr));
- PT=1.5*dpr;
- // Resizing clears the drawing buffer — repaint if the loop isn't running
- if(paused&&gl)drawFrame((performance.now()-startT)/1000);
+ const w=Math.max(1,Math.round(stage.clientWidth*dpr)),h=Math.max(1,Math.round(stage.clientHeight*dpr));
+ if(w===W&&h===H&&dpr===DPR)return false;
+ W=cvs.width=w;H=cvs.height=h;DPR=dpr;PT=1.5*dpr;
+ return true;
}
+// The loop keeps exactly one pending frame in raf. The clock adds up the time of each drawn frame (at most 50 ms, and a
+// third of it while Slow motion is on), so a pause never makes the particles jump.
function render(ts){
- if(paused){raf=null;return;}
raf=requestAnimationFrame(render);
- const dt=ts-lastT;if(dt<12)return;
- fpsEl.textContent=Math.round(1000/(dt||12))+' fps';lastT=ts;
- drawFrame((ts-startT)/1000);
+ if(last===null){last=ts;return;} // the first frame after a start only takes the time
+ const dt=ts-last;if(dt<12)return;
+ last=ts;
+ simT+=Math.min(dt,50)/1000/(slowTog.checked?3:1);
+ physics(simT);paint(simT);
}
-function drawFrame(t){
- // ── Physics pass (render to texture) ──
+// ── Physics pass (render to texture) ──
+function physics(t){
gl.useProgram(physicsProg);
gl.bindFramebuffer(gl.FRAMEBUFFER,fbo1);
gl.viewport(0,0,TEX_N,TEX_N);
@@ -276,16 +322,20 @@ function drawFrame(t){
gl.uniform1i(gl.getUniformLocation(physicsProg,'uPos'),0);
gl.uniform1f(gl.getUniformLocation(physicsProg,'uT'),t);
gl.uniform1f(gl.getUniformLocation(physicsProg,'uSpd'),SPD);
+ gl.uniform1f(gl.getUniformLocation(physicsProg,'uStep'),slowTog.checked?1/3:1);
gl.uniform1i(gl.getUniformLocation(physicsProg,'uBehavior'),BEHAVIOR);
gl.drawArrays(gl.TRIANGLE_STRIP,0,4);
// Swap textures
[tex0,tex1]=[tex1,tex0];[fbo0,fbo1]=[fbo1,fbo0];
+}
- // ── Render pass (draw points) ──
+// ── Render pass (draw points). A picture drawn on its own starts from a cleared canvas ("fresh"): with Trails on, a
+// normal frame only lays a thin fade over the last one, which would leave the old picture showing under a new setting. ──
+function paint(t,fresh){
gl.bindFramebuffer(gl.FRAMEBUFFER,null);
gl.viewport(0,0,W,H);
- if(TRAILS){// fade the previous frame instead of clearing it
+ if(TRAILS&&!fresh){// fade the previous frame instead of clearing it
gl.enable(gl.BLEND);gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA);
gl.useProgram(fadeProg);gl.bindBuffer(gl.ARRAY_BUFFER,qBuf);
const fa=gl.getAttribLocation(fadeProg,'a');gl.enableVertexAttribArray(fa);gl.vertexAttribPointer(fa,2,gl.FLOAT,false,0,0);
@@ -305,19 +355,24 @@ function drawFrame(t){
gl.disable(gl.BLEND);
}
-const pauseBtn=document.getElementById('pause-btn'),countSel=document.getElementById('count-sel');
-// Keep the select in sync with the small-screen default
-countSel.value=String(TEX_N);
-// While paused (including the reduced-motion hold) a control change still repaints once
-function refresh(){if(paused&&gl)drawFrame((performance.now()-startT)/1000);}
+// Play carries on from the clock and the particles where they stopped; it never stacks a second loop.
+function start(){if(raf!==null||!gl)return;last=null;raf=requestAnimationFrame(render);}
+// While paused a setting or a resize draws the picture again (no physics step), so the change shows without anything moving.
+function repaint(){if(paused&&gl)paint(simT,true);}
+
+// 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.
+document.addEventListener('hb:pause',e=>{
+ paused=e.detail.paused;
+ if(paused){if(raf!==null){cancelAnimationFrame(raf);raf=null;}}
+ else start();
+});
if(init()){
- startT=performance.now();lastT=startT;
- if(matchMedia('(prefers-reduced-motion: reduce)').matches){
- // Reduced motion: draw one static frame, never start the loop (user can opt in via Resume)
- paused=true;pauseBtn.textContent='▶ Resume';resize();
- }else{resize();raf=requestAnimationFrame(render);}
- window.addEventListener('resize',resize);
+ resize();
+ physics(simT);paint(simT,true); // the first picture, so a loop that is paused on arrival never shows an empty stage
+ start();
+ window.addEventListener('resize',()=>{if(resize()&&gl)paint(simT,true);});
cvs.addEventListener('webglcontextlost',e=>{
e.preventDefault();
if(raf!==null){cancelAnimationFrame(raf);raf=null;}
@@ -326,21 +381,30 @@ if(init()){
noWgl2.style.display='flex';
});
cvs.addEventListener('webglcontextrestored',()=>{
- if(init()){noWgl2.style.display='none';resize();startT=performance.now();lastT=startT;if(!paused)raf=requestAnimationFrame(render);}
+ if(!init())return;
+ noWgl2.style.display='none';
+ physics(simT);paint(simT,true);
+ if(!paused)start();
});
}
-countSel.addEventListener('change',e=>{TEX_N=+e.target.value;if(gl){initTex(TEX_N);refresh();}});
-document.getElementById('behav-sel').addEventListener('change',e=>{BEHAVIOR=+e.target.value;behavBadge.textContent=BEHAV_NAMES[BEHAVIOR];refresh();});
-document.getElementById('spd-sl').addEventListener('input',e=>{SPD=e.target.value/10;document.getElementById('spd-v').textContent=SPD.toFixed(1);refresh();});
-document.getElementById('col-sel').addEventListener('change',e=>{COLOR_MODE=+e.target.value;refresh();});
-document.getElementById('trail-tog').addEventListener('change',e=>{TRAILS=e.target.checked;refresh();});
-pauseBtn.addEventListener('click',()=>{
- paused=!paused;pauseBtn.textContent=paused?'▶ Resume':'⏸ Pause';
- if(raf!==null){cancelAnimationFrame(raf);raf=null;}// never stack a second loop
- if(!paused&&gl){lastT=performance.now();raf=requestAnimationFrame(render);}
+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);
+ }));
+}
+choices('move-seg',d=>{BEHAVIOR=+d.behavior;});
+choices('count-seg',d=>{
+ const n=+d.n;
+ if(n===TEX_N)return; // choosing what is already chosen must not scatter the particles again
+ TEX_N=n;
+ if(gl){initTex(TEX_N);repaint();}
});
+choices('speed-seg',d=>{SPD=+d.spd;});
+choices('color-seg',d=>{COLOR_MODE=+d.mode;repaint();});
+document.getElementById('trail-tog').addEventListener('change',e=>{TRAILS=e.target.checked;repaint();});
</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 47a6d5a5..275d64bd 100644
--- a/index.html
+++ b/index.html
@@ -1020,7 +1020,7 @@ const CATS=[
['chromatic-aberration','Chromatic Aberration','A word splits into red, green and blue fringes. Best for bold titles.'],
['2-5d-pseudo-3d','2.5D / Pseudo-3D','Seven depth layers parallax at different rates — mouse-driven or auto-panning camera.'],
['ray-marching-sdf','Ray Marching / SDF','A 3D scene drawn only from formulas, circled by a camera. Best for art pages.'],
- ['gpgpu-particle-system','GPGPU Particle System','65k+ particles computed in WebGL2 textures — physics in a shader, texture ping-pong.'],
+ ['gpgpu-particle-system','GPGPU Particle System','Tens of thousands of particles flow on the graphics chip. Best for hero effects.'],
['image-distortion-hover','Image Distortion on Hover','Fragment shader displaces UV coordinates around the cursor — ripple, push, liquid, pixelate.'],
['cloth-simulation','Cloth Simulation','Verlet integration + distance constraints — draggable flag responds to gravity and wind.'],
['volumetric-smoke','Volumetric Smoke','Ray marching accumulates 3D noise density — light scattering, shadow rays, fBm clouds.'],