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.
HTML ai-promptsanimationcss-animationsfrontendgithub-pagesjavascriptmicrointeractionsmotion-designno-dependenciesreferencescroll-animationui-animationweb-animationweb-developmentwebgl
feat: move Ray Marching / SDF Scene to the guided-steps page
matin500020a60ab2
diff --git a/animations/06-3d-advanced/ray-marching-sdf/README.md b/animations/06-3d-advanced/ray-marching-sdf/README.mdindex 06b959a4..685dd500 100644--- a/animations/06-3d-advanced/ray-marching-sdf/README.md+++ b/animations/06-3d-advanced/ray-marching-sdf/README.md@@ -1,7 +1,7 @@# Ray Marching / SDF Scene## What it is-Ray marching renders a 3D scene entirely inside a fragment shader without any mesh geometry. Instead of triangles, shapes are defined as Signed Distance Functions (SDFs) — mathematical functions that return the distance from any point in space to the nearest surface. A ray is cast for each pixel; the shader advances the ray forward by the SDF value at each step (which is always safe — the SDF guarantees no overshoot), repeating until the ray hits a surface or exits the scene. Everything visible is pure math.+Ray marching draws a 3D scene without any 3D models. Each shape is a formula that gives the distance to its surface, and for every pixel the shader steps a ray forward by that distance until it touches something, then lights that point. Because the shapes are formulas, they can melt together, be carved out of each other or repeat forever.## When to use it- Complex animated 3D shapes that are difficult to model as meshes (fractals, boolean blends, organic morphs)@@ -66,11 +66,12 @@ vec3 getNormal(vec3 p) {## Key parameters| Parameter | Default | Effect ||-----------|---------|--------|-| Max steps | 48 (32 on mobile) | More steps = finer detail on concave surfaces, but lower FPS |-| Resolution scale | 0.7× under 600px, DPR capped at 1.5× above | Cost is per pixel, so the backing store — not the scene — sets the frame time |-| Step scale | 0.9× | Multiplying by <1 trades performance for accuracy on thin features |-| Epsilon (hit distance) | 0.001 | Smaller = sharper surface but more steps required |-| Smooth-min k | 0.3–0.5 | Controls blend radius between shapes |+| Scene | Blend | Blend melts a sphere, a box and a ring together; Cut-out carves a box out of a sphere, with a small ball inside; Endless repeats a carved box across the floor without end |+| Camera speed | Normal | How fast the camera circles the shapes: once in about 18 seconds at slow, 10 at normal and 6 at fast |+| Soft shadows | off | Casts a second ray toward the light from every surface point, for soft shadows; the most costly option |+| Corner shading | on | Darkens creases and corners where surfaces meet, by testing a few points just above each surface |+| Detail | Medium | The most steps a ray may take: low is 24, medium 48 and high 96; phones take two thirds as many |+| Step count view | off | Colors each pixel by how many steps its ray took: edges and near misses take the most |## Production notes- **Shadertoy convention**: uniforms are `iTime`, `iResolution`, `iMouse`. Porting Shadertoy code to WebGL requires renaming these to your own uniform names and adding the WebGL boilerplate (vertex shader + quad).@@ -80,6 +81,6 @@ vec3 getNormal(vec3 p) {- **Three.js alternative**: Three.js with `ShaderMaterial` passes the same uniforms to the same fragment shader — the GLSL is identical, only the WebGL boilerplate changes.## See also-- [Volumetric Smoke](../volumetric-smoke/) — ray marching that accumulates density rather than finding surface hits-- [WebGL Shader Animation](../webgl-shader-animation/) — simpler fragment shaders on the same fullscreen-quad setup-- [Fluid Simulation](../fluid-simulation/) — SDF metaballs as a 2D application of the same SDF principle+- [Volumetric Smoke / 3D Noise](../volumetric-smoke/) — rays that add up smoke instead of stopping at a surface+- [WebGL Shader Animation](../webgl-shader-animation/) — simpler shaders on the same setup+- [Fluid / Liquid Simulation](../fluid-simulation/) — the same melting of shapes, in 2Ddiff --git a/animations/06-3d-advanced/ray-marching-sdf/index.html b/animations/06-3d-advanced/ray-marching-sdf/index.htmlindex bb356b13..46321052 100644--- a/animations/06-3d-advanced/ray-marching-sdf/index.html+++ b/animations/06-3d-advanced/ray-marching-sdf/index.html@@ -4,7 +4,7 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Ray Marching / SDF Scene — Animation Handbook</title>- <meta name="description" content="3D rendered entirely in a fragment shader — no meshes, no vertices. Every surface is pure math.">+ <meta name="description" content="A 3D scene drawn only from formulas, circled by a camera. Best for art pages."><link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/ray-marching-sdf/"><link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png"><link rel="icon" type="image/svg+xml" href="../../../favicon.svg">@@ -12,102 +12,147 @@<meta property="og:type" content="article"><meta property="og:site_name" content="Animation Handbook"><meta property="og:title" content="Ray Marching / SDF Scene — Animation Handbook">- <meta property="og:description" content="3D rendered entirely in a fragment shader — no meshes, no vertices. Every surface is pure math.">+ <meta property="og:description" content="A 3D scene drawn only from formulas, circled by a camera. Best for art pages."><meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/ray-marching-sdf/"><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="Ray Marching / SDF Scene — Animation Handbook">- <meta name="twitter:description" content="3D rendered entirely in a fragment shader — no meshes, no vertices. Every surface is pure math.">+ <meta name="twitter:description" content="A 3D scene drawn only from formulas, circled by a camera. Best for art pages."><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": "Ray Marching / SDF Scene", "name": "Ray Marching / SDF Scene", "description": "3D rendered entirely in a fragment shader — no meshes, no vertices. Every surface is pure math.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/ray-marching-sdf/", "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, Ray Marching / SDF Scene"}</script>+ <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "Ray Marching / SDF Scene", "name": "Ray Marching / SDF Scene", "description": "A 3D scene drawn only from formulas, circled by a camera. Best for art pages.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/ray-marching-sdf/", "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, Ray Marching / SDF Scene"}</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:#0b0b0d}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}- .badge{font-size:9px;color:rgba(255,255,255,.5);background:rgba(0,0,0,.4);padding:3px 8px;border-radius:4px;letter-spacing:.5px}- .src-panel{position:absolute;bottom:0;left:0;right:0;background:rgba(6,10,16,.93);border-top:1px solid var(--ui-border);padding:12px;font-size:8.5px;color:var(--ui-muted);font-family:monospace;line-height:1.5;max-height:220px;overflow-y:auto;display:none;white-space:pre-wrap;word-break:break-all}- .fallback{position:absolute;inset:0;display:none;flex-direction:column;justify-content:center;gap:8px;padding:clamp(16px,5vw,32px);background:var(--ui-bg);font-size:10px;line-height:1.7;color:var(--ui-muted);overflow-y:auto;white-space:pre-wrap}- .fallback strong{color:var(--ui-text);font-weight:400;font-size:11px}- 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}.stage{flex:none;width:100%}aside{width:100%}:root{--stage-h:380px}}+ .fallback{position:absolute;inset:0;display:none;flex-direction:column;justify-content:center;gap:8px;padding:clamp(16px,5vw,32px);background:#0b0b0d;font-size:13px;line-height:1.7;color:rgba(255,255,255,.72);overflow-y:auto;white-space:pre-wrap}+ .fallback strong{color:#f4f4f2;font-weight:600}</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="../2-5d-pseudo-3d/" rel="prev" title="Previous">‹ Prev</a><a class="ah-hideSm" href="../gpgpu-particle-system/" 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/ray-marching-sdf/index.html" target="_blank" rel="noopener noreferrer">Source ↗</a></span></div>-<header>- <h1>Ray Marching / SDF Scene</h1>- <p>3D rendered entirely in a fragment shader — no meshes, no vertices. Every surface is pure math.</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="scene-badge">Scene 1: Blend</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="../2-5d-pseudo-3d/" rel="prev" aria-label="Previous: 2.5D / Pseudo-3D"><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>2.5D / Pseudo-3D</span></a><a href="../gpgpu-particle-system/" rel="next" aria-label="Next: GPGPU Particle System"><span><span class="hb-dir">Next: </span>GPGPU Particle System</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.12 · 3D & Advanced</p>+ <h1>Ray Marching / SDF Scene</h1>+ <p class="hb-lede">A 3D scene drawn only from formulas, circled by a camera. Best for art pages.</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="A 3D scene of shapes on a floor, seen by a camera that keeps circling them"></canvas>+ <div class="fallback" id="fallback"></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="scene-lbl">Scene</p>+ <div class="seg" id="scene-seg" role="group" aria-labelledby="scene-lbl">+ <button type="button" data-scene="0" class="on" aria-pressed="true">Blend</button>+ <button type="button" data-scene="1" aria-pressed="false">Cut-out</button>+ <button type="button" data-scene="2" aria-pressed="false">Endless</button>+ </div>+ <p class="hb-hint">Shapes that melt, shapes cut from shapes, or endless copies.</p>+ </div>+ <div class="hb-setting">+ <p class="hb-setting-name" id="cam-lbl">Camera speed</p>+ <div class="seg" id="cam-seg" role="group" aria-labelledby="cam-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 fast the camera circles the shapes.</p>+ </div>+ <div class="hb-setting">+ <label class="hb-switch-row"><span>Soft shadows</span><input class="hb-switch" type="checkbox" role="switch" id="shadow-tog" autocomplete="off"></label>+ <p class="hb-hint">Real soft shadows; costly, so best left off on phones.</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">+ <label class="hb-switch-row"><span>Corner shading</span><input class="hb-switch" type="checkbox" role="switch" id="ao-tog" checked autocomplete="off"></label>+ <p class="hb-hint">Darkens creases where surfaces meet.</p>+ </div>+ <div class="hb-setting">+ <p class="hb-setting-name" id="detail-lbl">Detail</p>+ <div class="seg" id="detail-seg" role="group" aria-labelledby="detail-lbl">+ <button type="button" data-detail="0" aria-pressed="false">Low</button>+ <button type="button" data-detail="1" class="on" aria-pressed="true">Medium</button>+ <button type="button" data-detail="2" aria-pressed="false">High</button>+ </div>+ <p class="hb-hint">More steps find thin edges; phones use fewer.</p>+ </div>+ <div class="hb-setting">+ <label class="hb-switch-row"><span>Step count view</span><input class="hb-switch" type="checkbox" role="switch" id="debug-tog" autocomplete="off"></label>+ <p class="hb-hint">Colors each pixel by how many steps it took.</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 ray-marched 3D scene to [the section you want it in]. Draw the whole scene in a fragment shader, with no 3D models: describe each shape as a formula that gives the distance to its surface, then for every pixel step a ray forward by that distance until it touches a surface, and light that point. Formulas let shapes melt together, be carved out of each other or repeat without end, while a camera circles them. Every pixel does a lot of work, so draw fewer pixels and take fewer steps 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>++ <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="src-panel" id="src-panel"></div>- <div class="fallback" id="fallback"></div>- </div>- <aside>- <p class="note">No geometry exists. The "shape" is a function returning distance to the nearest surface at any point. The shader marches rays forward in steps equal to the SDF value — guaranteed to be safe.</p>- <div class="lbl">Scene</div>- <select id="scene-sel">- <option value="0" selected>Blend — sphere, box, torus</option>- <option value="1">Boolean — subtract & union</option>- <option value="2">Repetition — infinite grid</option>- </select>- <div class="lbl">Camera Speed</div>- <div class="sr"><input type="range" id="cam-sl" min="0" max="20" value="6" step="1"><span class="sv" id="cam-v">0.6</span></div>- <div class="lbl">Max March Steps</div>- <div class="sr"><input type="range" id="steps-sl" min="16" max="96" value="48" step="8"><span class="sv" id="steps-v">48</span></div>- <label class="tog"><input type="checkbox" id="ao-tog" checked><span>Ambient occlusion</span></label>- <label class="tog"><input type="checkbox" id="shadow-tog"><span>Soft shadows (GPU-heavy)</span></label>- <label class="tog"><input type="checkbox" id="debug-tog"><span>Debug: march steps as color</span></label>- <label class="tog"><input type="checkbox" id="src-tog"><span>View shader source</span></label>- <div class="div"></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>Art pages</li><li>Hero visuals</li><li>Tech demos</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>const VS=`attribute vec2 a;void main(){gl_Position=vec4(a,0.,1.);}`;const FS=`precision mediump float;-uniform vec2 uRes;uniform float uT,uCamSpd;uniform int uScene,uMaxSteps;uniform bool uAO,uShadow,uDebug;+uniform vec2 uRes;uniform float uT,uCamAng;uniform int uScene,uMaxSteps;uniform bool uAO,uShadow,uDebug;float sdSph(vec3 p,float r){return length(p)-r;}float sdBox(vec3 p,vec3 b){vec3 q=abs(p)-b;return length(max(q,0.))+min(max(q.x,max(q.y,q.z)),0.);}@@ -151,7 +196,7 @@ float softshadow(vec3 ro,vec3 rd){float t=.05,sh=1.;for(int i=0;i<20;i++){floatvoid main(){vec2 uv=(gl_FragCoord.xy-.5*uRes)/min(uRes.x,uRes.y);- float angle=uT*uCamSpd;+ float angle=uCamAng;vec3 ro=vec3(sin(angle)*3.8,.6+sin(uT*.2)*.3,cos(angle)*3.8);vec3 ta=vec3(0.,-.1,0.);vec3 ww=normalize(ta-ro),uu=normalize(cross(ww,vec3(0,1,0))),vv=cross(uu,ww);@@ -187,19 +232,22 @@ void main(){}`;const stage=document.getElementById('stage'),cvs=document.getElementById('cvs');-const fpsEl=document.getElementById('fps'),sceneBadge=document.getElementById('scene-badge');-const srcPanel=document.getElementById('src-panel'),pauseBtn=document.getElementById('pause-btn'),fallback=document.getElementById('fallback');-const stepsSl=document.getElementById('steps-sl'),stepsV=document.getElementById('steps-v');-let W,H,gl,prog,U=null,raf=null,paused=false,lastT=0,startT=0,curT=0;-let SCENE=0,CAM_SPD=0.6,MAX_STEPS=48,AO=true,SHADOW=false,DEBUG=false;-const SCENE_NAMES=['Blend','Boolean','Repetition'];-const UNIFORMS=['uRes','uT','uCamSpd','uScene','uMaxSteps','uAO','uShadow','uDebug'];-const MOBILE=matchMedia('(max-width:600px)');+const fallback=document.getElementById('fallback'),slowTog=document.getElementById('slow-tog');+let W=0,H=0,gl,prog,U=null,raf=null,paused=false,last=null,curT=0,camA=0;+let SCENE=0,CAM_SPD=0.6,DETAIL=1,AO=true,SHADOW=false,DEBUG=false;+const UNIFORMS=['uRes','uT','uCamAng','uScene','uMaxSteps','uAO','uShadow','uDebug'];+// The most steps a ray may take at Low, Medium and High: on computers, then on phones+const STEPS=[[24,48,96],[16,32,64]];+// Phones are screens up to 600px wide, or up to 500px tall when held sideways+const PHONE=matchMedia('(max-width:600px),(max-height:500px)');+function steps(){return STEPS[PHONE.matches?1:0][DETAIL];}+let MAX_STEPS=steps();// Cost is one full ray march per *pixel*, so the backing store is what sets the// bill. Phones render below CSS resolution and desktops cap DPR at 1.5.-function qScale(){const dpr=window.devicePixelRatio||1;return MOBILE.matches?Math.min(dpr,0.7):Math.min(dpr,1.5);}+function qScale(){const dpr=window.devicePixelRatio||1;return PHONE.matches?Math.min(dpr,0.7):Math.min(dpr,1.5);}function fail(msg,detail){+ cvs.hidden=true;fallback.style.display='flex';fallback.innerHTML='';const s=document.createElement('strong');s.textContent=msg;fallback.appendChild(s);@@ -207,6 +255,7 @@ function fail(msg,detail){}function init(){+ U=null;gl=cvs.getContext('webgl');if(!gl){fail('WebGL is unavailable in this browser.','The whole scene is a fragment shader — without a GL context there is no geometry left to draw. Try a browser with hardware acceleration enabled.');return false;}let log='';@@ -223,32 +272,37 @@ function init(){const a=gl.getAttribLocation(prog,'a');gl.enableVertexAttribArray(a);gl.vertexAttribPointer(a,2,gl.FLOAT,false,0,0);U={};UNIFORMS.forEach(n=>{U[n]=gl.getUniformLocation(prog,n);});- fallback.style.display='none';- srcPanel.textContent=FS;+ fallback.style.display='none';cvs.hidden=false;return true;}-function resize(){- const s=qScale();- W=cvs.width=Math.max(1,Math.round(stage.clientWidth*s));- H=cvs.height=Math.max(1,Math.round(stage.clientHeight*s));- if(gl&&U){gl.viewport(0,0,W,H);if(paused)draw(curT);}+// Sizes the canvas to the stage and the phone limits, and says whether anything changed. 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).+function layout(force){+ const s=qScale(),w=Math.max(1,Math.round(stage.clientWidth*s)),h=Math.max(1,Math.round(stage.clientHeight*s)),n=steps();+ if(!force&&w===W&&h===H&&n===MAX_STEPS)return false;+ W=cvs.width=w;H=cvs.height=h;MAX_STEPS=n;+ if(gl&&U)gl.viewport(0,0,W,H);+ return true;}-// Redraw a single frame so a control still shows its effect while paused.+// While paused a setting still draws the picture again, so its effect shows without anything moving.function refresh(){if(paused&&gl&&U)draw(curT);}+// The loop keeps exactly one pending frame in raf. The clock and the camera's angle add up the time of each drawn frame+// (at most 50 ms, and a third of it while Slow motion is on), so a pause or a new camera speed never makes the camera jump.function render(ts){- if(paused){raf=null;return;}raf=requestAnimationFrame(render);- const dt=ts-lastT;if(dt<16)return;- fpsEl.textContent=Math.round(1000/(dt||16))+' fps';lastT=ts;- draw((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<16)return;+ last=ts;+ const step=Math.min(dt,50)/1000/(slowTog.checked?3:1);+ curT+=step;camA+=step*CAM_SPD;+ draw(curT);}function draw(t){- curT=t;gl.useProgram(prog);gl.uniform2f(U.uRes,W,H);gl.uniform1f(U.uT,t);- gl.uniform1f(U.uCamSpd,CAM_SPD);+ gl.uniform1f(U.uCamAng,camA);gl.uniform1i(U.uScene,SCENE);gl.uniform1i(U.uMaxSteps,MAX_STEPS);gl.uniform1i(U.uAO,AO?1:0);@@ -257,35 +311,43 @@ function draw(t){gl.drawArrays(gl.TRIANGLE_STRIP,0,4);}-// Resume from the time we paused at so the camera does not jump; never stack a second loop.-function start(){lastT=performance.now();startT=lastT-curT*1000;if(raf===null)raf=requestAnimationFrame(render);}+// Play carries on from the clock and the angle it stopped at; it never stacks a second loop.+function start(){if(raf!==null||!gl||!U)return;last=null;raf=requestAnimationFrame(render);}function stop(){if(raf!==null)cancelAnimationFrame(raf);raf=null;}+// 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)stop();else start();+});+if(init()){- // Reduced-quality path for phones: fewer marches on top of the lower- // backing-store resolution picked in qScale().- if(MOBILE.matches){MAX_STEPS=32;stepsSl.value=String(MAX_STEPS);stepsV.textContent=MAX_STEPS;}- resize();- if(matchMedia('(prefers-reduced-motion:reduce)').matches){paused=true;pauseBtn.textContent='▶ Resume';draw(0);}- else start();- window.addEventListener('resize',resize);+ layout(true);+ draw(0); // the first picture, so a loop that is paused on arrival never shows an empty stage+ start();+ window.addEventListener('resize',()=>{if(layout()&&gl&&U)draw(curT);});cvs.addEventListener('webglcontextlost',e=>{e.preventDefault();stop();});- cvs.addEventListener('webglcontextrestored',()=>{init();resize();if(paused)draw(curT);else start();});+ cvs.addEventListener('webglcontextrestored',()=>{+ if(!init())return;+ layout(true);draw(curT);+ if(!paused)start();+ });}-document.getElementById('scene-sel').addEventListener('change',e=>{SCENE=+e.target.value;sceneBadge.textContent='Scene '+(SCENE+1)+': '+SCENE_NAMES[SCENE];refresh();});-document.getElementById('cam-sl').addEventListener('input',e=>{CAM_SPD=e.target.value/10;document.getElementById('cam-v').textContent=CAM_SPD.toFixed(1);refresh();});-stepsSl.addEventListener('input',e=>{MAX_STEPS=+e.target.value;stepsV.textContent=MAX_STEPS;refresh();});-document.getElementById('ao-tog').addEventListener('change',e=>{AO=e.target.checked;refresh();});+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('scene-seg',d=>{SCENE=+d.scene;refresh();});+choices('cam-seg',d=>{CAM_SPD=+d.spd;});+choices('detail-seg',d=>{DETAIL=+d.detail;MAX_STEPS=steps();refresh();});document.getElementById('shadow-tog').addEventListener('change',e=>{SHADOW=e.target.checked;refresh();});+document.getElementById('ao-tog').addEventListener('change',e=>{AO=e.target.checked;refresh();});document.getElementById('debug-tog').addEventListener('change',e=>{DEBUG=e.target.checked;refresh();});-document.getElementById('src-tog').addEventListener('change',e=>{srcPanel.style.display=e.target.checked?'block':'none';});-pauseBtn.addEventListener('click',()=>{- paused=!paused;pauseBtn.textContent=paused?'▶ Resume':'⏸ Pause';- if(!gl||!U)return;- if(paused)stop();else start();-});</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.htmlindex 35934e0c..47a6d5a5 100644--- a/index.html+++ b/index.html@@ -1019,7 +1019,7 @@ const CATS=[['svg-path-animation','SVG Path Animation','A line drawing draws itself, stroke by stroke. Best for icons and logos.'],['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','3D scene entirely in a fragment shader — sphere blend, boolean ops, infinite repetition.'],+ ['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.'],['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.'],