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
fix: audit and repair all 18 3D & Advanced demos (section 6)
matin830962527a19
diff --git a/animations/06-3d-advanced/2-5d-pseudo-3d/README.md b/animations/06-3d-advanced/2-5d-pseudo-3d/README.mdindex 9e7fa1ff..ec3dbd7b 100644--- a/animations/06-3d-advanced/2-5d-pseudo-3d/README.md+++ b/animations/06-3d-advanced/2-5d-pseudo-3d/README.md@@ -1,7 +1,7 @@# 2.5D / Pseudo-3D## What it is-2.5D (pseudo-3D) arranges flat 2D layers at different virtual depths using CSS `perspective` and `translateZ`, then moves a virtual "camera" to create a parallax depth illusion. Layers closest to the camera move the most in response to mouse or scroll; distant layers barely move. The technique was used in classic video games (Doom, old platformers) and animated films (Disney's multiplane camera, 1937), and translates directly to CSS with no additional libraries.+2.5D (pseudo-3D) arranges flat 2D layers at different virtual depths, then moves a virtual "camera" to create a parallax depth illusion. Layers closest to the camera move the most in response to mouse or scroll; distant layers barely move. The technique was used in classic video games (Doom, old platformers) and animated films (Disney's multiplane camera, 1937), and translates directly to CSS with no additional libraries.## When to use it- Hero sections with illustrated scenes that should feel dimensionaldiff --git a/animations/06-3d-advanced/2-5d-pseudo-3d/index.html b/animations/06-3d-advanced/2-5d-pseudo-3d/index.htmlindex b55c4070..10b6a3c8 100644--- a/animations/06-3d-advanced/2-5d-pseudo-3d/index.html+++ b/animations/06-3d-advanced/2-5d-pseudo-3d/index.html@@ -4,20 +4,20 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>2.5D / Pseudo-3D — Animation Handbook</title>- <meta name="description" content="Flat 2D layers at different CSS translateZ depths — mouse movement parallaxes each at a different rate.">+ <meta name="description" content="Flat 2D layers at seven virtual depths — mouse movement parallaxes each at a different rate."><link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/2-5d-pseudo-3d/"><link rel="icon" type="image/png" href="../../../favicon.png"><meta property="og:type" content="article"><meta property="og:site_name" content="Animation Handbook"><meta property="og:title" content="2.5D / Pseudo-3D — Animation Handbook">- <meta property="og:description" content="Flat 2D layers at different CSS translateZ depths — mouse movement parallaxes each at a different rate.">+ <meta property="og:description" content="Flat 2D layers at seven virtual depths — mouse movement parallaxes each at a different rate."><meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/2-5d-pseudo-3d/"><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="2.5D / Pseudo-3D — Animation Handbook">- <meta name="twitter:description" content="Flat 2D layers at different CSS translateZ depths — mouse movement parallaxes each at a different rate.">+ <meta name="twitter:description" content="Flat 2D layers at seven virtual depths — mouse movement parallaxes each at a different rate."><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": "2.5D / Pseudo-3D", "name": "2.5D / Pseudo-3D", "description": "Flat 2D layers at different CSS translateZ depths — mouse movement parallaxes each at a different rate.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/2-5d-pseudo-3d/", "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, 2.5D / Pseudo-3D"}</script>+ <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "2.5D / Pseudo-3D", "name": "2.5D / Pseudo-3D", "description": "Flat 2D layers at seven virtual depths — mouse movement parallaxes each at a different rate.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/2-5d-pseudo-3d/", "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, 2.5D / Pseudo-3D"}</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}@@ -98,7 +98,7 @@ body{padding-top:46px}<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="../chromatic-aberration/" rel="prev" title="Previous">‹ Prev</a><a class="ah-hideSm" href="../ray-marching-sdf/" 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/2-5d-pseudo-3d/index.html" target="_blank" rel="noopener noreferrer">Source ↗</a></span></div><header><h1>2.5D / Pseudo-3D</h1>- <p>Flat 2D layers at different CSS translateZ depths — mouse movement parallaxes each at a different rate.</p>+ <p>Flat 2D layers at seven virtual depths — mouse movement parallaxes each at a different rate.</p></header><div class="layout"><div class="stage" id="stage">@@ -233,14 +233,26 @@ document.getElementById('mode-sel').addEventListener('change',e=>{});document.getElementById('str-sl').addEventListener('input',e=>{strength=+e.target.value;document.getElementById('str-v').textContent=strength+'px';+ // A running auto-pan repaints itself next frame; every other state has to be redrawn here+ // or the new strength wouldn't show until the pointer moved again.+ if(!raf)applyParallax(mode==='auto'?.25:mx,mode==='auto'?.15:my);});document.getElementById('labels-tog').addEventListener('change',e=>{document.querySelectorAll('.depth-label').forEach(d=>d.style.display=e.target.checked?'block':'none');});document.getElementById('reset-btn').addEventListener('click',()=>{mx=0;my=0;autoT0=performance.now();mxV.textContent='—';applyParallax(0,0)});-// Hide labels by default; stagger them vertically so the seven layers' labels don't stack on one spot-document.querySelectorAll('.depth-label').forEach((d,i)=>{d.style.display='none';d.style.top=(4+i*12)+'px'});+// Hide labels by default; stagger them vertically so the seven layers' labels don't stack on one+// spot, and inset each by its own maximum camera travel so a panned layer never carries its label+// out past the clipped edge of the scene.+const MAX_PAN=+document.getElementById('str-sl').max*.5;+const SKY_INSET=6; // .sky is inset -6px, so its label starts outside the scene box+document.querySelectorAll('.depth-label').forEach((d,i)=>{+ const pad=i===0?SKY_INSET:0;+ d.style.display='none';+ d.style.top=(4+i*12+pad)+'px';+ d.style.right=(6+pad+MAX_PAN*LAYERS[i].depth)+'px';+});</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>diff --git a/animations/06-3d-advanced/3d-model-orbit/README.md b/animations/06-3d-advanced/3d-model-orbit/README.mdindex 62cf994c..70d5d11d 100644--- a/animations/06-3d-advanced/3d-model-orbit/README.md+++ b/animations/06-3d-advanced/3d-model-orbit/README.md@@ -64,6 +64,8 @@ const MVP = multiply(P, M);- **Normal matrix**: strictly, normals should be transformed by the inverse-transpose of the model matrix, not the model matrix itself. For uniform scaling (no non-uniform squash/stretch), the model matrix works fine. For non-uniform scale, use `mat3(transpose(inverse(uM)))`.- **`prefers-reduced-motion`**: stop the animation loop and show the object in its default orientation. The object should remain visible and interactive for camera control.- **Touch/pointer interaction**: use `pointerdown` / `pointermove` / `pointerup` for drag-to-rotate, not `mousedown` — this covers touch without separate event listeners.+- **Fail loudly**: a shader that does not compile produces a black canvas and no exception, because `COMPILE_STATUS` is only readable if you ask for it. Check it (and `LINK_STATUS`) and show a message; a silent black box is the hardest WebGL bug to diagnose.+- **Context loss**: the browser can drop a WebGL context on a GPU reset, driver update, or tab restore, and the canvas then stays blank forever. In production, listen for `webglcontextlost` (call `preventDefault()` on it) and rebuild buffers, textures, and programs in `webglcontextrestored`. This demo does not, to keep the render path readable.## See also- [Scroll-Driven 3D Rotation](../scroll-driven-3d-rotation/) — scroll position drives the rotation instead of timediff --git a/animations/06-3d-advanced/3d-model-orbit/index.html b/animations/06-3d-advanced/3d-model-orbit/index.htmlindex 7c7056e4..825ec9e9 100644--- a/animations/06-3d-advanced/3d-model-orbit/index.html+++ b/animations/06-3d-advanced/3d-model-orbit/index.html@@ -34,6 +34,7 @@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}.fps-badge,.obj-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}+ .msg{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;text-align:center;padding:24px;font-size:11px;line-height:1.7;color:var(--ui-muted)}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)}@@ -203,13 +204,25 @@ let MODE='orbit',WIRE=false,DIST=3,SX=.2,SY=.8,COLOR=[88/255,166/255,255/255];let mouseNX=0,mouseNY=0;const motionOk=!window.matchMedia('(prefers-reduced-motion:reduce)').matches;-function sh(t,s){const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);return x;}+// A failed shader is otherwise a silent black canvas — say so instead.+function fail(msg){gl=null;if(raf){cancelAnimationFrame(raf);raf=null;}+ cvs.style.display='none';fpsEl.textContent='—';+ const d=document.createElement('div');d.className='msg';d.textContent=msg;stage.appendChild(d);}+function sh(t,s){+ const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);+ if(!gl.getShaderParameter(x,gl.COMPILE_STATUS)){console.error(gl.getShaderInfoLog(x));return null;}+ return x;+}function init(){- gl=cvs.getContext('webgl');if(!gl)return;+ gl=cvs.getContext('webgl');+ if(!gl){fail('WebGL is unavailable in this browser, so there is nothing to render.');return;}+ const vs=sh(gl.VERTEX_SHADER,VS),fs=sh(gl.FRAGMENT_SHADER,FS);+ if(!vs||!fs){fail('Shader compilation failed — the log is in the browser console.');return;}prog=gl.createProgram();- gl.attachShader(prog,sh(gl.VERTEX_SHADER,VS));- gl.attachShader(prog,sh(gl.FRAGMENT_SHADER,FS));- gl.linkProgram(prog);gl.useProgram(prog);+ gl.attachShader(prog,vs);gl.attachShader(prog,fs);+ gl.linkProgram(prog);+ if(!gl.getProgramParameter(prog,gl.LINK_STATUS)){console.error(gl.getProgramInfoLog(prog));fail('Shader program failed to link — the log is in the browser console.');return;}+ gl.useProgram(prog);gl.enable(gl.DEPTH_TEST);gl.clearColor(.024,.039,.063,1);posBuf=gl.createBuffer();nrmBuf=gl.createBuffer();idxBuf=gl.createBuffer();lineBuf=gl.createBuffer();loadGeometry('cube');@@ -228,7 +241,12 @@ function loadGeometry(name){objBadge.textContent={cube:'Cube',sphere:'Sphere',torus:'Torus',tetra:'Tetrahedron'}[name];}-function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;if(gl)gl.viewport(0,0,W,H);}+// Backing store in device pixels (capped at 2x) so the render is not upscaled on retina.+function resize(){+ const d=Math.min(window.devicePixelRatio||1,2);+ W=cvs.width=Math.round(stage.clientWidth*d);H=cvs.height=Math.round(stage.clientHeight*d);+ if(gl)gl.viewport(0,0,W,H);+}function setAttr(name,buf,size){gl.bindBuffer(gl.ARRAY_BUFFER,buf);@@ -265,9 +283,10 @@ function render(ts){}init();resize();-if(!gl){fpsEl.textContent='WebGL unavailable';}-else if(motionOk){lastT=performance.now();raf=requestAnimationFrame(render);}-else{draw();} // reduced motion: one static frame, object stays visible+if(gl){+ if(motionOk){lastT=performance.now();raf=requestAnimationFrame(render);}+ else{draw();} // reduced motion: one static frame, object stays visible+}stage.addEventListener('pointermove',e=>{const r=cvs.getBoundingClientRect();mouseNX=(e.clientX-r.left)/r.width*2-1;mouseNY=(e.clientY-r.top)/r.height*2-1;diff --git a/animations/06-3d-advanced/canvas-particle-effect/README.md b/animations/06-3d-advanced/canvas-particle-effect/README.mdindex ab6b475e..08afcc4e 100644--- a/animations/06-3d-advanced/canvas-particle-effect/README.md+++ b/animations/06-3d-advanced/canvas-particle-effect/README.md@@ -20,8 +20,10 @@ class Particle {const d2 = dx * dx + dy * dy;if (d2 < 14400 && d2 > 1) { // within 120pxconst d = Math.sqrt(d2);- this.vx += FORCE * (dx / d) / d * 0.8;- this.vy += FORCE * (dy / d) / d * 0.8;+ // (dx, dy) / d points away from the cursor, so subtracting FORCE+ // makes a negative value repel and a positive value attract.+ this.vx -= FORCE * (dx / d) / d * 0.8;+ this.vy -= FORCE * (dy / d) / d * 0.8;}// Speed capconst sp = Math.sqrt(this.vx**2 + this.vy**2);@@ -57,7 +59,7 @@ for (let i = 0; i < particles.length; i++) {## Key parameters| Parameter | Default | Effect ||-----------|---------|--------|-| Particle count | 400 | O(n²) connections — above 500 the loop becomes the bottleneck |+| Particle count | 500 (250 under 600px) | O(n²) connections — above 500 the loop becomes the bottleneck || Connection distance | 100px | Larger = denser mesh; smaller = isolated dots || Mouse force | –0.5 | Negative = repel; positive = attract; 0 = no interaction || Speed | 0.8px/frame | Faster = chaotic; slower = meditative |@@ -67,6 +69,7 @@ for (let i = 0; i < particles.length; i++) {- **Canvas vs DOM**: `<canvas>` is mandatory for 50+ particles. DOM elements at that density create thousands of layout calculations per frame — the browser cannot keep up.- **Particles.js / tsParticles**: the dominant production library. Handles everything in this demo plus themes, shape variety, responsive density, and performance at high counts.- **`ctx.clearRect` vs `fillRect`**: using `fillRect` with a semi-transparent background instead of `clearRect` creates a motion-trail effect where older frames linger (enable "trails" toggle in the demo).+- **Device pixel ratio**: size the backing store to `clientWidth * devicePixelRatio` (capped at 2) and scale the context, or sub-pixel dots and 0.5px connection lines blur on retina screens.- **`prefers-reduced-motion`**: stop all particle movement. Consider keeping the static dot layout visible as a texture.## See alsodiff --git a/animations/06-3d-advanced/canvas-particle-effect/index.html b/animations/06-3d-advanced/canvas-particle-effect/index.htmlindex a12253cb..213f726e 100644--- a/animations/06-3d-advanced/canvas-particle-effect/index.html+++ b/animations/06-3d-advanced/canvas-particle-effect/index.html@@ -4,20 +4,20 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Canvas Particle Effect — Animation Handbook</title>- <meta name="description" content="500 particles drifting with O(n²) proximity connections — mouse repels or attracts within a configurable radius.">+ <meta name="description" content="500 particles drifting with O(n²) proximity connections — mouse repels or attracts with configurable force."><link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/canvas-particle-effect/"><link rel="icon" type="image/png" href="../../../favicon.png"><meta property="og:type" content="article"><meta property="og:site_name" content="Animation Handbook"><meta property="og:title" content="Canvas Particle Effect — Animation Handbook">- <meta property="og:description" content="500 particles drifting with O(n²) proximity connections — mouse repels or attracts within a configurable radius.">+ <meta property="og:description" content="500 particles drifting with O(n²) proximity connections — mouse repels or attracts with configurable force."><meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/canvas-particle-effect/"><meta property="og:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="Canvas Particle Effect — Animation Handbook">- <meta name="twitter:description" content="500 particles drifting with O(n²) proximity connections — mouse repels or attracts within a configurable radius.">+ <meta name="twitter:description" content="500 particles drifting with O(n²) proximity connections — mouse repels or attracts with configurable force."><meta name="twitter:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">- <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "Canvas Particle Effect", "name": "Canvas Particle Effect", "description": "500 particles drifting with O(n²) proximity connections — mouse repels or attracts within a configurable radius.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/canvas-particle-effect/", "inLanguage": "en", "articleSection": "3D & Advanced", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, 3D & Advanced, Canvas Particle Effect"}</script>+ <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "Canvas Particle Effect", "name": "Canvas Particle Effect", "description": "500 particles drifting with O(n²) proximity connections — mouse repels or attracts with configurable force.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/canvas-particle-effect/", "inLanguage": "en", "articleSection": "3D & Advanced", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, 3D & Advanced, Canvas Particle Effect"}</script><style>@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}@@ -67,7 +67,7 @@ body{padding-top:46px}<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="../parallax-3d-tilt/" rel="prev" title="Previous">‹ Prev</a><a class="ah-hideSm" href="../fluid-simulation/" 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/canvas-particle-effect/index.html" target="_blank" rel="noopener noreferrer">Source ↗</a></span></div><header><h1>Canvas Particle Effect</h1>- <p>500 particles drifting with O(n²) proximity connections — mouse repels or attracts within a configurable radius.</p>+ <p>500 particles drifting with O(n²) proximity connections — mouse repels or attracts with configurable force.</p></header><div class="layout"><div class="stage" id="stage">@@ -102,7 +102,14 @@ let paused=false,raf=null,lastT=0,fps=0;let COUNT=500,DIST=100,SPD=0.8,FORCE=-0.5,COLOR='#58a6ff';let CONNECTIONS=true,TRAILS=false;-function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;}+// Backing store is scaled by DPR (capped at 2) so 0.5px lines and 1px dots stay crisp+// on retina screens; the context transform keeps all drawing in CSS pixels.+function resize(){+ const dpr=Math.min(window.devicePixelRatio||1,2);+ W=stage.clientWidth;H=stage.clientHeight;+ cvs.width=Math.round(W*dpr);cvs.height=Math.round(H*dpr);+ ctx.setTransform(dpr,0,0,dpr,0,0);+}class P{constructor(){this.reset();}@@ -115,7 +122,9 @@ class P{update(){const dx=this.x-mouse.x,dy=this.y-mouse.y;const d2=dx*dx+dy*dy;- if(d2<14400&&d2>1){const d=Math.sqrt(d2);this.vx+=FORCE*(dx/d)/d*.8;this.vy+=FORCE*(dy/d)/d*.8;}+ // (dx,dy)/d points away from the cursor, so subtracting FORCE makes+ // negative = repel and positive = attract, matching the slider label.+ if(d2<14400&&d2>1){const d=Math.sqrt(d2);this.vx-=FORCE*(dx/d)/d*.8;this.vy-=FORCE*(dy/d)/d*.8;}const maxV=SPD*2;const sp=Math.sqrt(this.vx*this.vx+this.vy*this.vy);if(sp>maxV){this.vx=this.vx/sp*maxV;this.vy=this.vy/sp*maxV;}this.x+=this.vx;this.y+=this.vy;@@ -134,6 +143,7 @@ function loop(t){raf=requestAnimationFrame(loop);const dt=t-lastT;if(dt<16){return;}lastT=t;fps=Math.round(1000/(dt||16));fpsEl.textContent=fps+' fps';+ particles.forEach(p=>p.update());draw();}@@ -144,8 +154,6 @@ function draw(){const hex=COLOR,r=parseInt(hex.slice(1,3),16),g=parseInt(hex.slice(3,5),16),b=parseInt(hex.slice(5,7),16);const d2max=DIST*DIST;- particles.forEach(p=>p.update());-// Connectionsif(CONNECTIONS){for(let i=0;i<particles.length;i++){@@ -185,12 +193,12 @@ stage.addEventListener('touchmove',e=>{const r=cvs.getBoundingClientRect();mousewindow.addEventListener('resize',()=>{resize();spawn();if(paused)draw();});document.getElementById('count-sl').addEventListener('input',e=>{COUNT=+e.target.value;document.getElementById('count-v').textContent=COUNT;document.getElementById('p-count').textContent=COUNT;spawn();if(paused)draw();});-document.getElementById('dist-sl').addEventListener('input',e=>{DIST=+e.target.value;document.getElementById('dist-v').textContent=DIST+'px';});+document.getElementById('dist-sl').addEventListener('input',e=>{DIST=+e.target.value;document.getElementById('dist-v').textContent=DIST+'px';if(paused)draw();});document.getElementById('spd-sl').addEventListener('input',e=>{const n=e.target.value/10,k=n/SPD;SPD=n;particles.forEach(p=>{p.vx*=k;p.vy*=k;});document.getElementById('spd-v').textContent=SPD.toFixed(1);});document.getElementById('force-sl').addEventListener('input',e=>{FORCE=e.target.value/10;document.getElementById('force-v').textContent=FORCE.toFixed(1);});-document.getElementById('color-pick').addEventListener('input',e=>{COLOR=e.target.value;});-document.getElementById('conn-tog').addEventListener('change',e=>{CONNECTIONS=e.target.checked;});-document.getElementById('trail-tog').addEventListener('change',e=>{TRAILS=e.target.checked;});+document.getElementById('color-pick').addEventListener('input',e=>{COLOR=e.target.value;if(paused)draw();});+document.getElementById('conn-tog').addEventListener('change',e=>{CONNECTIONS=e.target.checked;if(paused)draw();});+document.getElementById('trail-tog').addEventListener('change',e=>{TRAILS=e.target.checked;if(paused)draw();});document.getElementById('pause-btn').addEventListener('click',()=>{paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';if(!paused)start();diff --git a/animations/06-3d-advanced/cloth-simulation/README.md b/animations/06-3d-advanced/cloth-simulation/README.mdindex 3bf72b0b..b83ffac8 100644--- a/animations/06-3d-advanced/cloth-simulation/README.md+++ b/animations/06-3d-advanced/cloth-simulation/README.md@@ -73,7 +73,8 @@ for (let r = 0; r < ROWS; r++) {- **GPU cloth simulation**: AAA games simulate cloth on the GPU using compute shaders (DirectX/Vulkan/Metal) or GPGPU passes (same ping-pong texture technique as the GPGPU particle demo). WebGPU enables this in browsers as of Chrome 113+.- **Cannon.js / Rapier.js**: JavaScript physics engines that include cloth/soft-body simulation with more accuracy and more constraint types. Rapier (Rust/WASM) is the fastest modern option.- **Self-collision**: this demo does not prevent cloth from passing through itself (self-intersection). Self-collision detection is O(n²) and requires spatial hashing or BVH acceleration structures.-- **Performance**: at 40×30 resolution (1200 vertices, ~3600 constraints, 4 iterations = 14400 constraint solves per frame), expect ~45fps on mid-range mobile. Reduce to 16×12 for mobile.+- **Performance**: at 40×30 resolution (1200 vertices, ~3600 constraints, 4 iterations = 14400 constraint solves per frame), expect ~45fps on mid-range mobile. The demo starts at 16×12 under 600px for that reason; the resolution select still lets you push it higher.+- **Canvas resolution**: the backing store is sized to `devicePixelRatio` (capped at 2) and the context is scaled to match, so the mesh stays crisp on phones without paying for a 3× framebuffer.## See also- [GPGPU Particle System](../gpgpu-particle-system/) — GPU-computed physics using the texture ping-pong techniquediff --git a/animations/06-3d-advanced/cloth-simulation/index.html b/animations/06-3d-advanced/cloth-simulation/index.htmlindex 3382df86..abda4d12 100644--- a/animations/06-3d-advanced/cloth-simulation/index.html+++ b/animations/06-3d-advanced/cloth-simulation/index.html@@ -30,7 +30,7 @@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{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;overflow:hidden;position:relative;touch-action:none}canvas{display:block;width:100%;height:100%;touch-action:none;cursor:grab}.fps-badge{position:absolute;top:8px;right:8px;font-size:9px;color:rgba(255,255,255,.5);background:rgba(0,0,0,.4);padding:3px 8px;border-radius:4px}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}@@ -111,7 +111,13 @@ let SHOW_VERTS=false,SHOW_CONS=false;let pts=[],prev=[],pinned=[],constraints=[];let dragIdx=-1,dragMouse={x:0,y:0};-function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;}+// W/H stay in CSS pixels; the backing store is scaled by DPR so the mesh stays crisp.+function resize(){+ const dpr=Math.min(window.devicePixelRatio||1,2);+ W=stage.clientWidth;H=stage.clientHeight;+ cvs.width=Math.round(W*dpr);cvs.height=Math.round(H*dpr);+ ctx.setTransform(dpr,0,0,dpr,0,0);+}function initCloth(){const w=W*.8,h=H*.65;@@ -206,6 +212,8 @@ function loop(ts){}function start(){resize();initCloth();if(!paused&&!raf){lastT=performance.now();raf=requestAnimationFrame(loop);}}+// Mobile fallback: a coarser grid means far fewer constraint solves per frame.+if(matchMedia('(max-width:600px)').matches){COLS=16;ROWS=12;document.getElementById('res-sel').value='16';}document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';start();diff --git a/animations/06-3d-advanced/flip-card-3d/index.html b/animations/06-3d-advanced/flip-card-3d/index.htmlindex 62bf2151..12ee0752 100644--- a/animations/06-3d-advanced/flip-card-3d/index.html+++ b/animations/06-3d-advanced/flip-card-3d/index.html@@ -178,8 +178,12 @@ body{padding-top:46px}function toggle(){setFlipped(!card.classList.contains('flipped'));}// Trigger: click- // Hover trigger has no hover on touch devices, so a tap flips there instead- card.addEventListener('click',()=>{if(trigger==='click'||!canHover.matches)toggle();});+ // Hover trigger gives a touch a way in: a tap flips even in hover mode.+ // Gate on the pointer that actually acted, not on the device — a touch+ // laptop reports hover:hover, so a media query alone leaves tap dead there.+ let lastPointer='mouse';+ card.addEventListener('pointerdown',e=>{lastPointer=e.pointerType;});+ card.addEventListener('click',()=>{if(trigger==='click'||lastPointer==='touch'||!canHover.matches)toggle();});document.getElementById('flip-btn').addEventListener('click',toggle);// Keyboard — flip is reachable and operable without a pointercard.addEventListener('keydown',e=>{diff --git a/animations/06-3d-advanced/fluid-simulation/README.md b/animations/06-3d-advanced/fluid-simulation/README.mdindex 6ad61bfd..07fb9e80 100644--- a/animations/06-3d-advanced/fluid-simulation/README.md+++ b/animations/06-3d-advanced/fluid-simulation/README.md@@ -61,7 +61,9 @@ vec2 ballPosition(int i, float t) {## Production notes- **Real fluid simulation**: Navier-Stokes-based fluid (velocity fields, pressure, diffusion) requires full-screen texture updates per frame. Pavel DoGreat's WebGL Fluid Simulation (open source) is the go-to — it renders truly interactive fluid at 60fps using a series of physics passes.- **SDF metaballs are an approximation**: they look fluid but don't conserve volume, don't flow around obstacles, and don't respond to physical forces. For true fluid behavior, use a full simulation library.-- **Performance**: each additional metaball adds a distance evaluation per pixel. On a 1920×1080 canvas with 8 balls, that's ~16 million SDF evaluations per frame. This is why mobile frame rates drop — use a lower canvas resolution on mobile.+- **Performance**: each additional metaball adds a distance evaluation per pixel. On a 1920×1080 canvas with 8 balls, that's ~16 million SDF evaluations per frame. This is why mobile frame rates drop — use a lower canvas resolution on mobile. The demo caps the backing store at 2× device pixel ratio on desktop and 1.5× under 600px, which is the whole of its quality/cost dial.+- **Silent shader failure**: a shader that fails to compile throws nothing and logs nothing — you get a black canvas. Always check `COMPILE_STATUS` and `LINK_STATUS` and surface a message, as this demo does.+- **Context loss**: `webglcontextlost` fires on a GPU reset, a driver update, or a backgrounded tab being restored. Without a listener the canvas stays black permanently. Call `preventDefault()` on the loss event, stop the loop, and rebuild the program on `webglcontextrestored`.- **Shadertoy**: the metaball pattern is one of the classic Shadertoy exercises. [shadertoy.com](https://www.shadertoy.com) has hundreds of metaball variants.- **`prefers-reduced-motion`**: pause the animation. The blobs should remain visible in their default positions.diff --git a/animations/06-3d-advanced/fluid-simulation/index.html b/animations/06-3d-advanced/fluid-simulation/index.htmlindex 8f567d3e..70da1d9c 100644--- a/animations/06-3d-advanced/fluid-simulation/index.html+++ b/animations/06-3d-advanced/fluid-simulation/index.html@@ -100,7 +100,7 @@ const stage=document.getElementById('stage');const cvs=document.getElementById('cvs');const fpsEl=document.getElementById('fps');const noWgl=document.getElementById('no-webgl');-let W,H,gl,prog,raf=null,paused=false,lastT=0,startT=0,simT=0;+let W,H,gl,prog,U={},raf=null,paused=false,lastT=0,startT=0,simT=0;let BALLS=5,SMOOTH=.08,RAD=.14,SPD=.8,MOUSE_BALL=true,GLOW=true;let COLOR=[88/255,166/255,255/255],BG=[3/255,8/255,16/255];let mouseX=.5,mouseY=.5;@@ -140,14 +140,27 @@ void main(){gl_FragColor=vec4(col,1.);}`;+// A failed shader is otherwise a silent black canvas — say so instead.+function fail(msg){gl=null;cvs.style.display='none';fpsEl.style.display='none';+ noWgl.textContent=msg;noWgl.style.display='flex';}+function init(){gl=cvs.getContext('webgl');- if(!gl){noWgl.style.display='flex';return false;}- function sh(type,src){const s=gl.createShader(type);gl.shaderSource(s,src);gl.compileShader(s);return s;}+ if(!gl){fail('WebGL is unavailable in this browser, so there is nothing to render.');return false;}+ function sh(type,src){const s=gl.createShader(type);gl.shaderSource(s,src);gl.compileShader(s);+ if(!gl.getShaderParameter(s,gl.COMPILE_STATUS)){console.error(gl.getShaderInfoLog(s));return null;}+ return s;}+ const vs=sh(gl.VERTEX_SHADER,VS),fs=sh(gl.FRAGMENT_SHADER,FS);+ if(!vs||!fs){fail('Shader compilation failed — the log is in the browser console.');return false;}prog=gl.createProgram();- gl.attachShader(prog,sh(gl.VERTEX_SHADER,VS));- gl.attachShader(prog,sh(gl.FRAGMENT_SHADER,FS));+ gl.attachShader(prog,vs);+ gl.attachShader(prog,fs);gl.linkProgram(prog);+ if(!gl.getProgramParameter(prog,gl.LINK_STATUS)){console.error(gl.getProgramInfoLog(prog));+ fail('Shader program failed to link — the log is in the browser console.');return false;}+ gl.useProgram(prog);+ U={};'uRes uT uBalls uSmooth uRad uMouse uGlow uMouseBall uColor uBG'.split(' ')+ .forEach(n=>{U[n]=gl.getUniformLocation(prog,n);});const buf=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,buf);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),gl.STATIC_DRAW);@@ -158,8 +171,15 @@ function init(){}function resize(){- W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;- if(gl)gl.viewport(0,0,W,H);+ // Full DPR on desktop, capped lower on phones — every pixel costs one SDF+ // pass per metaball, so the backing store is the whole cost of this demo.+ const dpr=Math.min(window.devicePixelRatio||1,window.innerWidth<=600?1.5:2);+ W=cvs.width=Math.max(1,Math.round(stage.clientWidth*dpr));+ H=cvs.height=Math.max(1,Math.round(stage.clientHeight*dpr));+ if(!gl)return;+ gl.viewport(0,0,W,H);+ // Resizing wipes the drawing buffer; while paused nothing would redraw it.+ if(paused)render(lastT+16);}function render(ts){@@ -169,17 +189,16 @@ function render(ts){if(!paused){fpsEl.textContent=Math.round(1000/dt)+' fps';simT+=Math.min(dt,100)/1000*SPD;}lastT=ts;gl.useProgram(prog);- const u=(n)=>gl.getUniformLocation(prog,n);- gl.uniform2f(u('uRes'),W,H);- gl.uniform1f(u('uT'),simT);- gl.uniform1i(u('uBalls'),BALLS);- gl.uniform1f(u('uSmooth'),SMOOTH);- gl.uniform1f(u('uRad'),RAD);- gl.uniform2f(u('uMouse'),mouseX,mouseY);- gl.uniform1i(u('uGlow'),GLOW?1:0);- gl.uniform1i(u('uMouseBall'),MOUSE_BALL?1:0);- gl.uniform3fv(u('uColor'),COLOR);- gl.uniform3fv(u('uBG'),BG);+ gl.uniform2f(U.uRes,W,H);+ gl.uniform1f(U.uT,simT);+ gl.uniform1i(U.uBalls,BALLS);+ gl.uniform1f(U.uSmooth,SMOOTH);+ gl.uniform1f(U.uRad,RAD);+ gl.uniform2f(U.uMouse,mouseX,mouseY);+ gl.uniform1i(U.uGlow,GLOW?1:0);+ gl.uniform1i(U.uMouseBall,MOUSE_BALL?1:0);+ gl.uniform3fv(U.uColor,COLOR);+ gl.uniform3fv(U.uBG,BG);gl.drawArrays(gl.TRIANGLE_STRIP,0,4);}@@ -195,6 +214,13 @@ if(init()){// Shader uv.y is flipped to top-down, so the pointer y must be top-down too.stage.addEventListener('pointermove',e=>{const r=cvs.getBoundingClientRect();mouseX=(e.clientX-r.left)/r.width;mouseY=(e.clientY-r.top)/r.height;});window.addEventListener('resize',resize);+ // Without these a GPU reset or tab restore leaves the stage black forever.+ cvs.addEventListener('webglcontextlost',e=>{e.preventDefault();cancelAnimationFrame(raf);raf=null;});+ cvs.addEventListener('webglcontextrestored',()=>{+ if(!init())return;+ lastT=performance.now();resize();+ if(!paused)raf=requestAnimationFrame(render);+ });}document.getElementById('balls-sl').addEventListener('input',e=>{BALLS=+e.target.value;document.getElementById('balls-v').textContent=BALLS;});diff --git a/animations/06-3d-advanced/gpgpu-particle-system/README.md b/animations/06-3d-advanced/gpgpu-particle-system/README.mdindex 8a6ef710..93f71b8f 100644--- a/animations/06-3d-advanced/gpgpu-particle-system/README.md+++ b/animations/06-3d-advanced/gpgpu-particle-system/README.md@@ -22,6 +22,8 @@ uniform float uTime, uSpeed;uniform int uBehavior;out vec4 outColor; // write new positions+float hash(float n) { return fract(sin(n) * 43758.5); }+void main() {ivec2 coord = ivec2(gl_FragCoord.xy);vec4 p = texelFetch(uPos, coord, 0);@@ -37,9 +39,12 @@ void main() {}vx *= 0.985; vy *= 0.985; // dampingx += vx; y += vy;- // Wrap at boundaries- x = x > 1.2 ? -1.2 : x < -1.2 ? 1.2 : x;- y = y > 1.2 ? -1.2 : y < -1.2 ? 1.2 : y;+ // 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;+ float a = hash(n) * 6.2832, r = hash(n + 3.71) * 0.9 + 0.05;+ x = cos(a) * r; y = sin(a) * r; vx = 0.0; vy = 0.0;+ }outColor = vec4(x, y, vx, vy);}```@@ -64,13 +69,14 @@ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);in float aIndex;uniform sampler2D uPos;uniform vec2 uTexSize;+uniform float uPointSize; // 1.5 CSS px x devicePixelRatiovoid main() {int idx = int(aIndex);ivec2 co = ivec2(int(mod(aIndex, uTexSize.x)), idx / int(uTexSize.x));vec4 p = texelFetch(uPos, co, 0);gl_Position = vec4(p.xy, 0.0, 1.0);- gl_PointSize = 1.5;+ gl_PointSize = uPointSize;}```@@ -80,12 +86,17 @@ void main() {| 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 | Wrap or respawn | Wrap keeps particle count constant; respawn allows birth/death |+| 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 |## 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+).- **Three.js `GPUComputationRenderer`**: Three.js includes `GPUComputationRenderer` (in the `three/examples/jsm` path) which encapsulates the entire ping-pong texture pattern. It's the idiomatic production approach.- **WebGPU compute shaders**: WebGPU provides proper `@compute` shader stages for GPGPU, eliminating the "fragment shader as compute" workaround. As of 2024, WebGPU is available in Chrome 113+ but not yet in Firefox stable or Safari.+- **Wrap only survives a divergence-free field**: this demo's flow field pushes particles away from the x-axis, so it has a net outward drift. An earlier version wrapped at ±1.2 while only ±1.0 is visible; particles drifted into that invisible ring faster than they came back and the canvas faded to black after about ten seconds. Tightening the wrap to ±1.0 only moved the symptom — a divergent field teleports the escapee straight back to the edge it just left, so the particles crust along the top and bottom instead. Respawning escapees at a random point near the middle is the fix, and it is what keeps the population steady here. Nothing throws in either failure, and the first second looks correct in all three versions, so this class of bug is only visible if you leave the demo running.+- **Point size is in device pixels**: the canvas backing store is sized `clientWidth * devicePixelRatio` (capped at 2 here) and `gl.viewport` uses those same numbers. `gl_PointSize` is measured in device pixels too, so it has to be multiplied by the same ratio or the points shrink on a retina screen.+- **Context loss**: a GPU reset, a tab restore, or too many live WebGL contexts will fire `webglcontextlost`. Without a listener that calls `preventDefault()`, the context never comes back and the demo stays black forever. On `webglcontextrestored` every program, buffer, texture and framebuffer has to be recreated — GPU objects do not survive the loss.+- **Mobile budget**: 65k additively blended points cover a phone screen several times over and are both slow and visually mushy. This demo drops to a 128x128 texture (16k particles) under 600px; a production system should scale the texture size to the pixel count it actually has to fill.- **Memory**: 256×256 × 4 channels × 4 bytes (float32) = 1MB per texture. Two textures = 2MB — trivial. At 512×512 (262k particles): 4MB × 2 = 8MB.## See alsodiff --git a/animations/06-3d-advanced/gpgpu-particle-system/index.html b/animations/06-3d-advanced/gpgpu-particle-system/index.htmlindex d174ba6b..f51f29c1 100644--- a/animations/06-3d-advanced/gpgpu-particle-system/index.html+++ b/animations/06-3d-advanced/gpgpu-particle-system/index.html@@ -144,9 +144,13 @@ void main(){}vx*=.985;vy*=.985;// dampingx+=vx;y+=vy;- // wrap- x=x>1.2?-1.2:x<-1.2?1.2:x;- y=y>1.2?-1.2:y<-1.2?1.2:y;+ // 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.){+ float n=float(co.x)*.0713+float(co.y)*.1319+uT*.977;+ float a=hash(n)*6.2832,r=hash(n+3.71)*.9+.05;+ x=cos(a)*r;y=sin(a)*r;vx=0.;vy=0.;+ }outCol=vec4(x,y,vx,vy);}`;@@ -155,7 +159,7 @@ const RENDER_VS=`#version 300 esprecision highp float;in float aIdx;uniform sampler2D uPos;uniform vec2 uTexSz;-uniform int uColorMode;uniform float uT;+uniform int uColorMode;uniform float uT;uniform float uPS;out vec4 vCol;void main(){int idx=int(aIdx);@@ -163,7 +167,7 @@ void main(){int ty=idx/int(uTexSz.x);vec4 p=texelFetch(uPos,ivec2(tx,ty),0);gl_Position=vec4(p.xy,0.,1.);- gl_PointSize=1.5;+ gl_PointSize=uPS;// 1.5 CSS px, scaled by devicePixelRatiofloat spd=length(p.zw)*200.;if(uColorMode==0)vCol=vec4(.35,.65,1.,.6);else if(uColorMode==1)vCol=vec4(spd*.8,spd*.4,1.-spd*.4,.7);@@ -182,12 +186,15 @@ const fpsEl=document.getElementById('fps'),countBadge=document.getElementById('cconst 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=256,BEHAVIOR=0,SPD=0.6,COLOR_MODE=0,TRAILS=false;-let idxBuf=null,particleCount=0;+let paused=false,lastT=0,startT=0,TEX_N=SMALL?128:256,BEHAVIOR=0,SPD=0.6,COLOR_MODE=0,TRAILS=false;+let idxBuf=null,particleCount=0,PT=1.5,shaderErr='';-function mk(t,s){const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);if(!gl.getShaderParameter(x,gl.COMPILE_STATUS))console.error(gl.getShaderInfoLog(x));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))console.error(gl.getProgramInfoLog(p));return p;}+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;}function initTex(n){const data=new Float32Array(n*n*4);@@ -223,10 +230,13 @@ function init(){// preserveDrawingBuffer keeps last frame for trails; alpha:false avoids premultiplied-alpha artifactsgl=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.style.display='flex';return false;}+ if(!gl||!gl.getExtension('EXT_color_buffer_float')){noWgl2.innerHTML=NO_WGL2_MSG;noWgl2.style.display='flex';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;}// Full-screen quad shared by the physics pass and the trail fadeqBuf=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);@@ -234,15 +244,25 @@ function init(){return true;}-function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;}+// Backing store follows devicePixelRatio (capped at 2) so points stay crisp, not upscaled+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);+}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;- const t=(ts-startT)/1000;+ drawFrame((ts-startT)/1000);+}+function drawFrame(t){// ── Physics pass (render to texture) ──gl.useProgram(physicsProg);gl.bindFramebuffer(gl.FRAMEBUFFER,fbo1);@@ -278,25 +298,41 @@ function render(ts){gl.uniform2f(gl.getUniformLocation(renderProg,'uTexSz'),TEX_N,TEX_N);gl.uniform1i(gl.getUniformLocation(renderProg,'uColorMode'),COLOR_MODE);gl.uniform1f(gl.getUniformLocation(renderProg,'uT'),t);+ gl.uniform1f(gl.getUniformLocation(renderProg,'uPS'),PT);gl.drawArrays(gl.POINTS,0,particleCount);gl.disable(gl.BLEND);}-const pauseBtn=document.getElementById('pause-btn');+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);}+if(init()){- resize();startT=performance.now();lastT=startT;- window.addEventListener('resize',resize);+ startT=performance.now();lastT=startT;if(matchMedia('(prefers-reduced-motion: reduce)').matches){- // Reduced motion: draw one static frame, leave the loop stopped (user can opt in via Resume)- render(startT+16);cancelAnimationFrame(raf);raf=null;paused=true;pauseBtn.textContent='▶ Resume';- }else raf=requestAnimationFrame(render);+ // 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);+ cvs.addEventListener('webglcontextlost',e=>{+ e.preventDefault();+ if(raf!==null){cancelAnimationFrame(raf);raf=null;}+ gl=null;tex0=tex1=idxBuf=null;+ noWgl2.textContent='WebGL context lost — waiting for the browser to restore it.';+ noWgl2.style.display='flex';+ });+ cvs.addEventListener('webglcontextrestored',()=>{+ if(init()){noWgl2.style.display='none';resize();startT=performance.now();lastT=startT;if(!paused)raf=requestAnimationFrame(render);}+ });}-document.getElementById('count-sel').addEventListener('change',e=>{TEX_N=+e.target.value;if(gl)initTex(TEX_N);});-document.getElementById('behav-sel').addEventListener('change',e=>{BEHAVIOR=+e.target.value;behavBadge.textContent=BEHAV_NAMES[BEHAVIOR];});-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=>{COLOR_MODE=+e.target.value;});-document.getElementById('trail-tog').addEventListener('change',e=>{TRAILS=e.target.checked;});+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 loopdiff --git a/animations/06-3d-advanced/image-distortion-hover/README.md b/animations/06-3d-advanced/image-distortion-hover/README.mdindex 8d85069d..8e08fbd3 100644--- a/animations/06-3d-advanced/image-distortion-hover/README.md+++ b/animations/06-3d-advanced/image-distortion-hover/README.md@@ -31,16 +31,14 @@ void main() {}```-The `uPhase` uniform advances each frame to animate the ripple outward even after the mouse stops. A **decay** multiplier fades the phase when the mouse is absent:+The `uPhase` uniform advances each frame to animate the ripple outward even after the mouse stops. A separate **amplitude** term is what fades: it is pinned to 1 while the pointer is over the stage and decays exponentially once the pointer leaves, so the distortion settles back to the undisplaced image rather than snapping off.```js-// Advance phase while mouse is present; decay when absent-if (mouseActive) {- phase += 0.05;-} else {- phase *= Math.max(0, 1 - DECAY * 0.016); // exponential decay-}+// Phase always advances; amplitude decays when the pointer is gone+phase += dt * 0.003;+if (!pointerActive) amp *= Math.max(0, 1 - DECAY * dt / 1000);gl.uniform1f(uPhase, phase);+gl.uniform1f(uStrength, STRENGTH * amp);```For a **procedural texture** (no external image required), generate the pattern in the same shader:@@ -63,6 +61,9 @@ vec3 pattern(vec2 uv) {## Production notes- **Real images**: replace the procedural `pattern()` function with `texture2D(uTexture, distortedUV)`. Load images into WebGL via `gl.texImage2D()` from an `<img>` or `ImageBitmap`. Same-origin policy applies — external image URLs need CORS headers.- **`gl.clampToEdge`**: ensure texture wrap mode is `CLAMP_TO_EDGE` so UV values outside [0,1] don't tile or mirror at the image border when distortion pushes UVs out of range.+- **Pointer, not mouse**: bind `pointermove`/`pointerdown` rather than `mousemove`, or the effect never fires on a phone. The cursor position must be converted to backing-store pixels (multiply by the device pixel ratio used for the canvas) before it reaches the shader, or the distortion centre drifts away from the finger on high-DPI screens.+- **Backing store and DPR**: size the canvas to `clientWidth * dpr` and call `gl.viewport()` after every resize. Uncapped DPR is expensive for a fullscreen fragment shader — this demo caps it at 2, and at 1.5 on phones. Resizing clears the drawing buffer, so a paused or reduced-motion demo has to repaint after a resize or it goes black.+- **Context loss**: a GPU reset or a restored tab fires `webglcontextlost`. Without a listener (and a `preventDefault()` so `webglcontextrestored` follows) the canvas dies permanently. Shaders, buffers and uniform locations all have to be rebuilt on restore.- **CSS-only alternative**: CSS `filter: blur()` and `transform: translate()` on pseudo-elements can approximate push distortion for a single element at low intensity. WebGL is needed for per-pixel wave and liquid effects.- **hover-effect-curtains / Curtains.js**: production libraries that wrap this exact pattern. They handle texture loading, canvas sizing, and the shader boilerplate. The GLSL fragment shader is identical to what this demo uses.- **Shader Park**: a higher-level tool for declaring distortion effects with a JavaScript-like syntax that compiles to GLSL. Suitable for creative applications where writing raw GLSL is a barrier.diff --git a/animations/06-3d-advanced/image-distortion-hover/index.html b/animations/06-3d-advanced/image-distortion-hover/index.htmlindex 85682f82..ed1cdf2a 100644--- a/animations/06-3d-advanced/image-distortion-hover/index.html+++ b/animations/06-3d-advanced/image-distortion-hover/index.html@@ -46,7 +46,9 @@.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%;min-height:44px}@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:flex;align-items:center;justify-content:center;text-align:center;padding:24px;font-size:11px;line-height:1.7;color:var(--ui-muted);white-space:pre-wrap}+ @media(max-width:600px){.layout{flex-direction:column}.stage{flex:none;width:100%}aside{width:100%}:root{--stage-h:380px}+ .tog input{width:44px;height:44px}}</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}@@ -141,25 +143,44 @@ void main(){const stage=document.getElementById('stage'),cvs=document.getElementById('cvs');const fpsEl=document.getElementById('fps'),srcPanel=document.getElementById('src-panel');-let W,H,gl,prog,raf=null,paused=false,lastT=0,startT=0;+let W,H,DPR=1,gl,prog,U={},raf=null,paused=false,lastT=0,startT=0,lastDraw=0,glErr='';let TYPE=0,STR=8,RAD=0.25,DECAY=0.5,ANIMATE=true;let mouseX=-999,mouseY=-999,phase=0,amp=0,active=false,t0=0;function init(){- gl=cvs.getContext('webgl');if(!gl)return false;- function sh(t,s){const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);return x;}- prog=gl.createProgram();- gl.attachShader(prog,sh(gl.VERTEX_SHADER,VS));- gl.attachShader(prog,sh(gl.FRAGMENT_SHADER,FS));- gl.linkProgram(prog);+ gl=cvs.getContext('webgl');+ if(!gl){glErr='WebGL is unavailable in this browser, so the distortion shader cannot run.';return false;}+ function sh(t,s){+ const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);+ if(!gl.getShaderParameter(x,gl.COMPILE_STATUS))throw new Error(gl.getShaderInfoLog(x)||'shader compile failed');+ return x;+ }+ try{+ prog=gl.createProgram();+ gl.attachShader(prog,sh(gl.VERTEX_SHADER,VS));+ gl.attachShader(prog,sh(gl.FRAGMENT_SHADER,FS));+ gl.linkProgram(prog);+ if(!gl.getProgramParameter(prog,gl.LINK_STATUS))throw new Error(gl.getProgramInfoLog(prog)||'program link failed');+ }catch(e){glErr=('Shader failed to build:\n'+e.message).replace(/\0/g,'').trim();return false;}+ U={};['uRes','uMouse','uT','uStr','uRad','uPhase','uType','uAnimate'].forEach(n=>{U[n]=gl.getUniformLocation(prog,n);});const buf=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,buf);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),gl.STATIC_DRAW);const a=gl.getAttribLocation(prog,'a');gl.enableVertexAttribArray(a);gl.vertexAttribPointer(a,2,gl.FLOAT,false,0,0);return true;}-function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;if(gl)gl.viewport(0,0,W,H);}-function u(n){return gl.getUniformLocation(prog,n);}+function resize(){+ // Cap the backing store: full DPR is wasted on a fullscreen fragment shader,+ // and phones pay for every extra pixel.+ DPR=Math.min(window.devicePixelRatio||1,innerWidth<=600?1.5:2);+ W=cvs.width=Math.max(1,Math.round(stage.clientWidth*DPR));+ H=cvs.height=Math.max(1,Math.round(stage.clientHeight*DPR));+ if(gl)gl.viewport(0,0,W,H);+ poke();+}+// Resizing the canvas clears it, and control changes are invisible while+// paused — repaint the held frame in both cases.+function poke(){if(paused&&gl&&prog)draw(lastDraw||t0);}function render(ts){if(paused){raf=null;return;}@@ -171,15 +192,16 @@ function render(ts){draw(ts);}function draw(ts){+ lastDraw=ts;gl.useProgram(prog);- gl.uniform2f(u('uRes'),W,H);- gl.uniform2f(u('uMouse'),mouseX,mouseY);- gl.uniform1f(u('uT'),(ts-t0)/1000);- gl.uniform1f(u('uStr'),STR*amp);- gl.uniform1f(u('uRad'),RAD);- gl.uniform1f(u('uPhase'),phase);- gl.uniform1i(u('uType'),TYPE);- gl.uniform1i(u('uAnimate'),ANIMATE?1:0);+ gl.uniform2f(U.uRes,W,H);+ gl.uniform2f(U.uMouse,mouseX,mouseY);+ gl.uniform1f(U.uT,(ts-t0)/1000);+ gl.uniform1f(U.uStr,STR*amp);+ gl.uniform1f(U.uRad,RAD);+ gl.uniform1f(U.uPhase,phase);+ gl.uniform1i(U.uType,TYPE);+ gl.uniform1i(U.uAnimate,ANIMATE?1:0);gl.drawArrays(gl.TRIANGLE_STRIP,0,4);}@@ -190,7 +212,8 @@ if(init()){// Reduced motion: show one static frame; the user can opt in with Resume.paused=true;document.getElementById('pause-btn').textContent='▶ Resume';fpsEl.textContent='paused';draw(t0);}else raf=requestAnimationFrame(render);- const track=e=>{const r=cvs.getBoundingClientRect();mouseX=e.clientX-r.left;mouseY=e.clientY-r.top;active=true;amp=1;};+ // Pointer, not mouse: touch and pen drive the distortion the same way.+ const track=e=>{const r=cvs.getBoundingClientRect();mouseX=(e.clientX-r.left)*DPR;mouseY=(e.clientY-r.top)*DPR;active=true;amp=1;};const release=()=>{active=false;};stage.addEventListener('pointermove',track);stage.addEventListener('pointerdown',track);@@ -198,13 +221,27 @@ if(init()){stage.addEventListener('pointerup',e=>{if(e.pointerType!=='mouse')release();});stage.addEventListener('pointercancel',release);window.addEventListener('resize',resize);-}else fpsEl.textContent='WebGL unavailable';+ cvs.addEventListener('webglcontextlost',e=>{+ e.preventDefault();if(raf)cancelAnimationFrame(raf);raf=null;fpsEl.textContent='context lost';+ });+ cvs.addEventListener('webglcontextrestored',()=>{+ if(!init())return;+ resize();+ if(paused)draw(lastDraw||performance.now());+ else{lastT=startT=performance.now();raf=requestAnimationFrame(render);}+ fpsEl.textContent='— fps';+ });+}else{+ fpsEl.textContent='—';+ const msg=document.createElement('div');msg.className='fallback';msg.textContent=glErr;+ stage.appendChild(msg);+}-document.getElementById('type-sel').addEventListener('change',e=>{TYPE=+e.target.value;});-document.getElementById('str-sl').addEventListener('input',e=>{STR=+e.target.value;document.getElementById('str-v').textContent=STR;});-document.getElementById('rad-sl').addEventListener('input',e=>{RAD=e.target.value/100;document.getElementById('rad-v').textContent=RAD.toFixed(2);});+document.getElementById('type-sel').addEventListener('change',e=>{TYPE=+e.target.value;poke();});+document.getElementById('str-sl').addEventListener('input',e=>{STR=+e.target.value;document.getElementById('str-v').textContent=STR;poke();});+document.getElementById('rad-sl').addEventListener('input',e=>{RAD=e.target.value/100;document.getElementById('rad-v').textContent=RAD.toFixed(2);poke();});document.getElementById('dec-sl').addEventListener('input',e=>{DECAY=e.target.value/10;document.getElementById('dec-v').textContent=DECAY.toFixed(1);});-document.getElementById('ripple-tog').addEventListener('change',e=>{ANIMATE=e.target.checked;});+document.getElementById('ripple-tog').addEventListener('change',e=>{ANIMATE=e.target.checked;poke();});document.getElementById('src-tog').addEventListener('change',e=>{srcPanel.style.display=e.target.checked?'block':'none';});document.getElementById('pause-btn').addEventListener('click',()=>{paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';diff --git a/animations/06-3d-advanced/morphing-blob/README.md b/animations/06-3d-advanced/morphing-blob/README.mdindex 77353460..9e8b4a30 100644--- a/animations/06-3d-advanced/morphing-blob/README.md+++ b/animations/06-3d-advanced/morphing-blob/README.md@@ -14,7 +14,7 @@ Each blob is a normal SVG `<circle>`. The whole group is passed through a "goo"```html<filter id="goo">- <feGaussianBlur in="SourceGraphic" stdDeviation="10" id="blur"/>+ <feGaussianBlur in="SourceGraphic" stdDeviation="10" id="blur" result="blur"/><feColorMatrix in="blur" mode="matrix"values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 20 -9" result="goo"/><feBlend in="SourceGraphic" in2="goo"/>@@ -28,18 +28,23 @@ The last row of the matrix (`0 0 0 20 -9`) is the trick: it multiplies alpha byif (b.droplet){ // Pointer Events → works for mouse, pen, touchb.x += (pointer.x - b.x) * 0.09; // attraction toward the cursorb.y += (pointer.y - b.y) * 0.09;-} else {- b.x = b.bx + Math.sin(time*speed*b.sx + b.px) * b.ax;- b.y = b.by + Math.cos(time*speed*b.sy + b.py) * b.ay;+} else { // phase += dt * speed, integrated per frame+ b.x = b.bx + Math.sin(phase*b.sx + b.px) * b.ax;+ b.y = b.by + Math.cos(phase*b.sy + b.py) * b.ay;}```+The drift phase is integrated (`phase += dt * speed`) rather than computed from+absolute time. Multiplying the elapsed time by the speed makes every blob jump to+a new point on its sine path the moment the speed changes; accumulating the phase+changes the rate and leaves the positions continuous.+## Key parameters| Parameter | Default | Effect ||-----------|---------|--------|| Gooeyness (`stdDeviation`) | 10 | Blur radius — higher fuses circles from farther apart and rounds the whole blob || Blob count | 6 | More circles = more complex, lumpier morphing; fewer = calmer |-| Drift speed | 1.0 | Multiplies the sine time — 0 freezes drift, higher churns faster |+| Drift speed | 1.0 | Rate the sine phase accumulates — 0 freezes drift, higher churns faster || Contrast row | `20 -9` | The alpha threshold; larger multiplier = crisper edge, smaller = softer/foggier || Droplet lerp | 0.09 | How eagerly the pointer droplet chases the cursor (higher = snappier) |diff --git a/animations/06-3d-advanced/morphing-blob/index.html b/animations/06-3d-advanced/morphing-blob/index.htmlindex 961651c5..554bf59a 100644--- a/animations/06-3d-advanced/morphing-blob/index.html+++ b/animations/06-3d-advanced/morphing-blob/index.html@@ -75,7 +75,7 @@ body{padding-top:46px}pushed through a steep contrast curve so soft edges snap back to ahard silhouette — overlapping circles fuse into one liquid shape. --><filter id="goo">- <feGaussianBlur in="SourceGraphic" stdDeviation="10" id="blur"/>+ <feGaussianBlur in="SourceGraphic" stdDeviation="10" id="blur" result="blur"/><feColorMatrix in="blur" mode="matrix"values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 20 -9" result="goo"/><feBlend in="SourceGraphic" in2="goo"/>@@ -115,7 +115,7 @@ const stage=document.getElementById('stage');const reduce=matchMedia('(prefers-reduced-motion:reduce)').matches;const CX=200,CY=200; // viewBox centre-let blobs=[],speed=1;+let blobs=[],speed=1,phase=0,last=0; // phase accumulates so a speed change never jumpslet pointer={x:CX,y:CY,active:false}; // target for the droplet, in viewBox unitsfunction build(n){@@ -142,12 +142,17 @@ function build(n){function frame(t){const time=t/1000;+ // Integrate the speed instead of multiplying absolute time: moving the drift+ // slider then changes the rate without teleporting the blobs. The clamp stops+ // a long background-tab pause from arriving as one huge step.+ phase+=Math.min(time-last,0.1)*speed;+ last=time;for(const b of blobs){if(b.droplet){b.x+=(pointer.x-b.x)*0.09; // lerp toward the pointer (attraction)b.y+=(pointer.y-b.y)*0.09;}else{- const w=time*speed;+ const w=phase;b.x=b.bx+Math.sin(w*b.sx+b.px)*b.ax;b.y=b.by+Math.cos(w*b.sy+b.py)*b.ay;}diff --git a/animations/06-3d-advanced/noise-based-motion/README.md b/animations/06-3d-advanced/noise-based-motion/README.mdindex d71d2f99..8aa73dc5 100644--- a/animations/06-3d-advanced/noise-based-motion/README.md+++ b/animations/06-3d-advanced/noise-based-motion/README.md@@ -56,7 +56,8 @@ ctx.closePath();| Noise scale | 0.008 | Small = large smooth patterns (zoomed in); large = fine rapid variation || Time speed | 0.5 | How fast the noise "advects" — low = glacial; high = turbulent || Amplitude | 12px | Displacement magnitude — how far points move from their rest position |-| Octaves (fbm) | 4 | More octaves = more detail at multiple scales (fractal brownian motion) |+| Grid density | 20 | Columns across the stage — spacing is `floor(W / density)` |+| Blob vertices | 48 | Segment count around the blob; too few reads as a polygon |## Production notes- **Simplex vs Perlin**: Simplex noise (Gustavson 2005) is faster and has fewer directional artifacts than classic Perlin noise. Use Simplex for new projects.diff --git a/animations/06-3d-advanced/noise-based-motion/index.html b/animations/06-3d-advanced/noise-based-motion/index.htmlindex 2df4b24b..ef8419a9 100644--- a/animations/06-3d-advanced/noise-based-motion/index.html+++ b/animations/06-3d-advanced/noise-based-motion/index.html@@ -124,10 +124,15 @@ const stage=document.getElementById('stage');const fpsEl=document.getElementByIdlet W,H,paused=false,raf=null,lastT=0,t=0;let MODE='grid',SCALE=.008,SPD=.5,AMP=12,GRID=20,VERTS=48,COLOR='#58a6ff';-function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;}+function resize(){+ const dpr=Math.min(window.devicePixelRatio||1,2);+ W=stage.clientWidth;H=stage.clientHeight;+ cvs.width=Math.round(W*dpr);cvs.height=Math.round(H*dpr);+ ctx.setTransform(dpr,0,0,dpr,0,0); // draw in CSS pixels, render at device resolution+}function drawGrid(){- const step=Math.floor(W/GRID);+ const step=Math.max(4,Math.floor(W/GRID)); // never 0 — a 0 step would loop foreverconst r=parseInt(COLOR.slice(1,3),16),g=parseInt(COLOR.slice(3,5),16),b=parseInt(COLOR.slice(5,7),16);for(let x=step/2;x<W;x+=step){for(let y=step/2;y<H;y+=step){@@ -186,7 +191,7 @@ if(matchMedia('(prefers-reduced-motion: reduce)').matches){paused=true;document.getElementById('pause-btn').textContent='▶ Resume';frame();}else{raf=requestAnimationFrame(loop);}-document.getElementById('mode-sel').addEventListener('change',e=>MODE=e.target.value);+document.getElementById('mode-sel').addEventListener('change',e=>{MODE=e.target.value;if(paused)frame();});document.getElementById('scale-sl').addEventListener('input',e=>{SCALE=e.target.value/1000;document.getElementById('scale-v').textContent=(SCALE).toFixed(3);});document.getElementById('spd-sl').addEventListener('input',e=>{SPD=e.target.value/10;document.getElementById('spd-v').textContent=SPD.toFixed(1);});document.getElementById('amp-sl').addEventListener('input',e=>{AMP=+e.target.value;document.getElementById('amp-v').textContent=AMP+'px';});diff --git a/animations/06-3d-advanced/parallax-3d-tilt/README.md b/animations/06-3d-advanced/parallax-3d-tilt/README.mdindex 5c0c5b64..c52a5539 100644--- a/animations/06-3d-advanced/parallax-3d-tilt/README.md+++ b/animations/06-3d-advanced/parallax-3d-tilt/README.md@@ -12,8 +12,10 @@ Parallax 3D tilt rotates a card in three dimensions as the mouse moves across it## How it works`perspective` must be set on the **parent**, not the card. The card's `rotateX`/`rotateY` are computed from cursor position relative to the card's center, normalized to ±maxAngle:+Bind **pointer** events, not mouse events — the same handler then covers mouse, pen and touch:+```js-card.addEventListener('mousemove', e => {+card.addEventListener('pointermove', e => {const r = card.getBoundingClientRect();const x = (e.clientX - r.left) / r.width - 0.5; // -0.5 to 0.5const y = (e.clientY - r.top) / r.height - 0.5;@@ -25,7 +27,7 @@ card.addEventListener('mousemove', e => {card.style.transform = `rotateX(${rx}deg) rotateY(${ry}deg) scale(1.03)`;});-card.addEventListener('mouseleave', () => {+card.addEventListener('pointerleave', () => {card.style.transform = 'rotateX(0deg) rotateY(0deg) scale(1)';});```@@ -40,16 +42,16 @@ shine.style.background = `radial-gradient()`;```-**Reset transition** — only apply `transition` on mouse-leave, not on mouse-move:+**Reset transition** — only apply `transition` on leave, not while tracking:```js-card.addEventListener('mousemove', () => card.classList.add('active'));-card.addEventListener('mouseleave', () => card.classList.remove('active'));+card.addEventListener('pointermove', () => card.classList.add('active'));+card.addEventListener('pointerleave', () => card.classList.remove('active'));``````css.card { transition: transform 400ms ease, box-shadow 400ms ease; }-.card.active { transition: none; } /* instant tracking on mousemove */+.card.active { transition: none; } /* instant tracking while the pointer moves */```## Key parameters@@ -61,10 +63,12 @@ card.addEventListener('mouseleave', () => card.classList.remove('active'));| Scale on hover | 1.03 | Subtle lift; pairing with shadow depth increase adds more realism |## Production notes-- **Touch devices**: `:hover` does not fire on touch. Add `:active` fallback with reduced tilt, or skip the effect on `(hover: none)` media query.+- **Touch devices**: use Pointer Events (`pointerdown`/`pointermove`/`pointerleave`) plus `touch-action: none` and the effect works on touch for free — a drag tilts the card, a tap sets it once. Do not gate the effect on `@media (hover: hover)`: hybrid touchscreen laptops match it, and a phone with a paired mouse can match it too, so branching on the media query kills the interaction on real devices. If you need to branch, branch on the live `event.pointerType`.- **`will-change: transform`**: add only during hover (`mouseenter`/`mouseleave`) to avoid permanent GPU layer allocation. Permanent `will-change` on many cards multiplies GPU memory use.- **VanillaTilt.js**: a zero-dependency library that handles this pattern with configurable tilt, glare, scale, and perspective. 2KB gzipped — use in production rather than hand-rolling.-- **Performance**: `rotateX`/`rotateY` on a GPU-composited element runs at 60fps with no paint. Avoid animating `box-shadow` simultaneously — shadows trigger paint.+- **`overflow: hidden` flattens 3D**: any ancestor with `overflow` other than `visible` (or a `filter`, or `opacity < 1`) forces `transform-style` to its flat used value, so `translateZ` on a child silently does nothing. A card that clips its own contents therefore cannot also be a `preserve-3d` container — give it its own `perspective` so its inner depth layers still project, or move the clip to a wrapper outside the 3D chain.+- **Performance**: `rotateX`/`rotateY` on a GPU-composited element runs at 60fps with no paint. Avoid animating `box-shadow` simultaneously — shadows trigger paint; the demo does it for the depth cue on a single card, but it is not something to repeat across a grid.+- **Reduced motion**: under `prefers-reduced-motion: reduce` the demo pins the card flat and hides the shine, leaving the numeric readout so the mechanic is still legible.## See also- [3D Model Orbit](../3d-model-orbit/) — full WebGL 3D rather than CSS 3Ddiff --git a/animations/06-3d-advanced/parallax-3d-tilt/index.html b/animations/06-3d-advanced/parallax-3d-tilt/index.htmlindex ad435cfd..776d5074 100644--- a/animations/06-3d-advanced/parallax-3d-tilt/index.html+++ b/animations/06-3d-advanced/parallax-3d-tilt/index.html@@ -38,8 +38,11 @@background:linear-gradient(135deg,#0d2040,#1a3060);border:1px solid rgba(255,255,255,.15);box-shadow:0 20px 60px rgba(0,0,0,.6);- transform-style:preserve-3d;- transform:perspective(var(--perspective)) rotateX(0deg) rotateY(0deg) scale(1);+ /* overflow:hidden above flattens transform-style:preserve-3d, so the depth+ layers get their own local perspective instead. The card's own rotation is+ projected by the perspective on .stage, never by a perspective() here. */+ perspective:var(--perspective);+ transform:rotateX(0deg) rotateY(0deg) scale(1);transition:transform var(--reset-dur) ease,box-shadow var(--reset-dur) ease;cursor:pointer;touch-action:none;will-change:transform@@ -74,7 +77,7 @@.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}@media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:auto}.stage{height:auto;min-height:420px;padding:32px 16px}}- @media(prefers-reduced-motion:reduce){.tilt-card{transition:none!important;transform:none!important}}+ @media(prefers-reduced-motion:reduce){.tilt-card{transition:none!important;transform:none!important}.card-shine{opacity:0!important;transition:none!important}.float-orb{transform:none!important}}</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}@@ -106,7 +109,7 @@ body{padding-top:46px}<div class="card-over">Feature card</div><div class="card-h">Three-dimensional perspective</div><div class="card-sub">Mouse position maps to rotateX and rotateY. The highlight follows the virtual light source.</div>- <div class="card-tag">Move mouse over card →</div>+ <div class="card-tag">Move or drag the card →</div></div><div class="readout" id="readout">rotX: 0° rotY: 0°</div></div>@@ -170,6 +173,7 @@ body{padding-top:46px}readout.textContent='rotX: 0° rotY: 0°';}+ card.addEventListener('pointerdown',onMove);card.addEventListener('pointermove',onMove);card.addEventListener('pointerleave',onLeave);card.addEventListener('pointercancel',onLeave);diff --git a/animations/06-3d-advanced/ray-marching-sdf/README.md b/animations/06-3d-advanced/ray-marching-sdf/README.mdindex 8aca6efc..06b959a4 100644--- a/animations/06-3d-advanced/ray-marching-sdf/README.md+++ b/animations/06-3d-advanced/ray-marching-sdf/README.md@@ -66,7 +66,8 @@ vec3 getNormal(vec3 p) {## Key parameters| Parameter | Default | Effect ||-----------|---------|--------|-| Max steps | 48 | More steps = finer detail on concave surfaces, but lower FPS |+| 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 |diff --git a/animations/06-3d-advanced/ray-marching-sdf/index.html b/animations/06-3d-advanced/ray-marching-sdf/index.htmlindex c6dd5b60..731b6b3a 100644--- a/animations/06-3d-advanced/ray-marching-sdf/index.html+++ b/animations/06-3d-advanced/ray-marching-sdf/index.html@@ -35,6 +35,8 @@.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)}@@ -77,6 +79,7 @@ body{padding-top:46px}<div class="badge" id="scene-badge">Scene 1: Blend</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>@@ -183,27 +186,53 @@ 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');-let W,H,gl,prog,raf=null,paused=false,lastT=0,startT=0,curT=0;+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)');++// 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 fail(msg,detail){+ fallback.style.display='flex';+ fallback.innerHTML='';+ const s=document.createElement('strong');s.textContent=msg;fallback.appendChild(s);+ if(detail){const p=document.createElement('div');p.textContent=detail;fallback.appendChild(p);}+}function init(){- gl=cvs.getContext('webgl');if(!gl)return false;- function sh(t,s){const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);if(!gl.getShaderParameter(x,gl.COMPILE_STATUS))console.error(gl.getShaderInfoLog(x));return x;}+ 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='';+ function sh(t,s){const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);if(!gl.getShaderParameter(x,gl.COMPILE_STATUS))log+=(gl.getShaderInfoLog(x)||'shader compile failed')+'\n';return x;}prog=gl.createProgram();gl.attachShader(prog,sh(gl.VERTEX_SHADER,VS));gl.attachShader(prog,sh(gl.FRAGMENT_SHADER,FS));gl.linkProgram(prog);+ if(!gl.getProgramParameter(prog,gl.LINK_STATUS))log+=(gl.getProgramInfoLog(prog)||'program link failed')+'\n';+ // A failed compile normally leaves a silent black canvas — say so instead.+ if(log){console.error(log);fail('The shader failed to build on this GPU.',log.trim());return false;}const buf=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,buf);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),gl.STATIC_DRAW);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;return true;}-function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;if(gl){gl.viewport(0,0,W,H);if(paused)draw(curT);}}-function u(n){return gl.getUniformLocation(prog,n);}+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);}+}+// Redraw a single frame so a control still shows its effect while paused.+function refresh(){if(paused&&gl&&U)draw(curT);}function render(ts){if(paused){raf=null;return;}@@ -215,14 +244,14 @@ function render(ts){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.uniform1i(u('uScene'),SCENE);- gl.uniform1i(u('uMaxSteps'),MAX_STEPS);- gl.uniform1i(u('uAO'),AO?1:0);- gl.uniform1i(u('uShadow'),SHADOW?1:0);- gl.uniform1i(u('uDebug'),DEBUG?1:0);+ gl.uniform2f(U.uRes,W,H);+ gl.uniform1f(U.uT,t);+ gl.uniform1f(U.uCamSpd,CAM_SPD);+ gl.uniform1i(U.uScene,SCENE);+ gl.uniform1i(U.uMaxSteps,MAX_STEPS);+ gl.uniform1i(U.uAO,AO?1:0);+ gl.uniform1i(U.uShadow,SHADOW?1:0);+ gl.uniform1i(U.uDebug,DEBUG?1:0);gl.drawArrays(gl.TRIANGLE_STRIP,0,4);}@@ -231,6 +260,9 @@ function start(){lastT=performance.now();startT=lastT-curT*1000;if(raf===null)rafunction stop(){if(raf!==null)cancelAnimationFrame(raf);raf=null;}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();@@ -239,16 +271,16 @@ if(init()){cvs.addEventListener('webglcontextrestored',()=>{init();resize();if(paused)draw(curT);else start();});}-document.getElementById('scene-sel').addEventListener('change',e=>{SCENE=+e.target.value;sceneBadge.textContent='Scene '+(SCENE+1)+': '+SCENE_NAMES[SCENE];});-document.getElementById('cam-sl').addEventListener('input',e=>{CAM_SPD=e.target.value/10;document.getElementById('cam-v').textContent=CAM_SPD.toFixed(1);});-document.getElementById('steps-sl').addEventListener('input',e=>{MAX_STEPS=+e.target.value;document.getElementById('steps-v').textContent=MAX_STEPS;});-document.getElementById('ao-tog').addEventListener('change',e=>{AO=e.target.checked;});-document.getElementById('shadow-tog').addEventListener('change',e=>{SHADOW=e.target.checked;});-document.getElementById('debug-tog').addEventListener('change',e=>{DEBUG=e.target.checked;});+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();});+document.getElementById('shadow-tog').addEventListener('change',e=>{SHADOW=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)return;+ if(!gl||!U)return;if(paused)stop();else start();});</script>diff --git a/animations/06-3d-advanced/scroll-driven-3d-rotation/index.html b/animations/06-3d-advanced/scroll-driven-3d-rotation/index.htmlindex 9068a659..439f08e3 100644--- a/animations/06-3d-advanced/scroll-driven-3d-rotation/index.html+++ b/animations/06-3d-advanced/scroll-driven-3d-rotation/index.html@@ -212,6 +212,9 @@ function onScroll(){}stageEl.addEventListener('scroll',onScroll,{passive:true});+// Resizing changes scrollHeight/clientHeight without firing a scroll event,+// so progress would stay frozen at its old value until the next scroll.+new ResizeObserver(()=>{if(stageEl.scrollTop>0)onScroll();}).observe(stageEl);document.getElementById('mult-sl').addEventListener('input',e=>{mult=+e.target.value;document.getElementById('mult-v').textContent=(mult/10).toFixed(1)+'×';onScroll();});diff --git a/animations/06-3d-advanced/svg-path-animation/README.md b/animations/06-3d-advanced/svg-path-animation/README.mdindex 1aab7036..a512b91f 100644--- a/animations/06-3d-advanced/svg-path-animation/README.md+++ b/animations/06-3d-advanced/svg-path-animation/README.md@@ -63,7 +63,7 @@ path.addEventListener('transitionend', () => {## Production notes- **`getTotalLength()` is required**: hardcoding `stroke-dasharray` breaks when the path changes. Always measure at runtime. For SVGs loaded asynchronously, measure after the element is added to the DOM.-- **Path direction**: the stroke draws from the path's start point (first `M` command). To control which end draws first, reverse the path data or animate in reverse (offset from 0 to length).+- **Path direction**: the stroke draws from the path's start point (first `M` command). To control which end draws first, reverse the path data, or start from a *negative* offset (`-length` → `0`), which hides the stroke the same way but uncovers it from the far end. Animating `0` → `length` is a different effect: it erases an already-drawn path.- **`stroke-dasharray` shorthand**: `stroke-dasharray: length length` (repeated) and `stroke-dasharray: length` are equivalent — a single value sets both dash and gap to the same length.- **GSAP DrawSVG plugin**: handles `getTotalLength()`, offset calculation, and animation sequencing automatically. Essential for complex multi-path illustrations. `gsap.from(path, { drawSVG: 0 })`.- **Framer Motion**: `<motion.path initial={{ pathLength: 0 }} animate={{ pathLength: 1 }} />` — `pathLength` is a 0–1 shorthand that internally manages `dasharray`/`dashoffset`.diff --git a/animations/06-3d-advanced/svg-path-animation/index.html b/animations/06-3d-advanced/svg-path-animation/index.htmlindex 44824cf2..a28890a6 100644--- a/animations/06-3d-advanced/svg-path-animation/index.html+++ b/animations/06-3d-advanced/svg-path-animation/index.html@@ -33,11 +33,11 @@.stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;background:#04060c;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:16px;padding:24px;position:relative}svg{width:100%;max-width:400px;overflow:visible}.draw-path{- fill:none;stroke:var(--stroke-color);stroke-width:var(--stroke-w);+ fill:none;fill-opacity:.15;stroke:var(--stroke-color);stroke-width:var(--stroke-w);stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:1;stroke-dashoffset:1;}- .draw-path.fill-done{fill:rgba(88,166,255,.15);transition:fill .4s ease}+ .draw-path.fill-done{fill:var(--stroke-color);transition:fill .4s ease}.preset-tabs{display:flex;gap:6px}.ptab{background:none;border:1px solid var(--ui-border);color:var(--ui-muted);font-family:monospace;font-size:10px;padding:6px 14px;border-radius:4px;cursor:pointer;min-height:44px;transition:border-color .15s,color .15s}.ptab.active{border-color:var(--ui-accent);color:var(--ui-accent)}@@ -134,7 +134,7 @@ const PRESETS=[name:'Logo',label:'Logo Mark',paths:[// Circle + inner geometric shape- 'M 200 40 A 120 120 0 1 1 199.99 40',+ 'M 200 10 A 120 120 0 1 1 199.99 10','M 200 80 L 240 150 L 200 130 L 160 150 Z','M 200 130 L 200 185',]@@ -184,14 +184,14 @@ function animate(paths){paths.forEach((path,i)=>{const len=path.getTotalLength();path.style.strokeDasharray=len;- path.style.strokeDashoffset=rev?0:len;+ path.style.strokeDashoffset=rev?-len:len;path.style.transition='none';const delay=i*(dur*0.3);setTimeout(()=>{if(id!==run)return;path.getBoundingClientRect(); // flush the hidden state so the transition has a start valuepath.style.transition=`stroke-dashoffset ${dur}ms ${ease}`;- path.style.strokeDashoffset=rev?len:0;+ path.style.strokeDashoffset=0;const isLast=i===paths.length-1;if(isLast){setTimeout(()=>{@@ -226,7 +226,10 @@ document.getElementById('sw-sl').addEventListener('input',e=>{document.getElementById('color-pick').addEventListener('input',e=>{document.documentElement.style.setProperty('--stroke-color',e.target.value);});-document.getElementById('ease-sel').addEventListener('change',()=>{});+document.getElementById('loop-tog').addEventListener('change',e=>{+ if(!e.target.checked){clearTimeout(loopTimer);return}+ if(!animating)replay();+});replay();</script>diff --git a/animations/06-3d-advanced/volumetric-smoke/README.md b/animations/06-3d-advanced/volumetric-smoke/README.mdindex 3c08bada..d69e79e9 100644--- a/animations/06-3d-advanced/volumetric-smoke/README.md+++ b/animations/06-3d-advanced/volumetric-smoke/README.md@@ -19,7 +19,7 @@ void main() {vec3 rd = normalize(vec3(uv, -0.9)); // ray directionfloat transmittance = 1.0;- vec3 color = uBackground;+ vec3 color = vec3(0.0); // background is composited once, at the endfloat stepSize = 3.0 / float(uSteps);for (int i = 0; i < MAX_STEPS; i++) {@@ -48,7 +48,8 @@ void main() {```glslfloat smokeDensity(vec3 p, float t) {float r = length(p.xz);- float src = exp(-r * 3.0) * smoothstep(-0.2, 0.6, p.y) * smoothstep(1.8, 1.0, p.y);+ // smoothstep needs edge0 < edge1, so the upper falloff is inverted rather than reversed+ float src = exp(-r * 3.0) * smoothstep(-0.2, 0.6, p.y) * (1.0 - smoothstep(1.0, 1.8, p.y));float n = fbm(p * 1.4 + vec3(windDrift, t * speed, 0.0));return max(0.0, n - 0.45) * src * density;}@@ -63,7 +64,10 @@ float smokeDensity(vec3 p, float t) {| Step size | `3.0 / steps` | Smaller steps = finer detail but more iterations needed |## Production notes-- **Step count vs quality**: each additional march step increases pixel cost linearly. 32 steps is generally sufficient for soft smoke; use 64 only for hero-quality renders. Add blue-noise dithering to random-offset each ray's start, breaking up banding artifacts at low step counts.+- **Precision**: the `sin`-based hash multiplies by 43758.5, which overflows the usable range of a 16-bit `mediump` float and collapses the noise to flat blocks on many mobile GPUs. Request `highp` in the fragment shader (guarded by `GL_FRAGMENT_PRECISION_HIGH`) or swap the hash for an integer-free variant with a smaller multiplier.+- **Mobile cost**: this is fill-rate bound — every fragment runs `steps x (fbm + 3 shadow taps)`. Honouring a 3x phone DPR would multiply the cost ninefold, so the demo caps the backing store at 0.75 CSS pixels and the march at 48 steps below 600px, and never exceeds 1 CSS pixel on desktop.+- **Context loss**: a GPU reset, a backgrounded tab on mobile, or a driver hiccup fires `webglcontextlost`. Without a listener the canvas goes permanently black with no error. Preventing the default event and rebuilding shaders and buffers on `webglcontextrestored` is the production path; this demo takes the simpler route of stopping the loop and showing a message.+- **Step count vs quality**: each additional march step increases pixel cost linearly. 32 steps is generally sufficient for soft smoke; use 64 only for hero-quality renders. Add blue-noise dithering to random-offset each ray's start, breaking up banding artifacts at low step counts. The offset has to be a fraction of a *full step* to help — jittering by a few thousandths of a unit is invisible.- **Shadow rays**: the 3-step shadow march adds 3× extra density samples per lit pixel. Toggle off on low-end devices. For production, pre-compute a voxelized shadow map and sample it instead.- **Real-time fire and smoke**: game engines use particle systems with additive-blended sprite sheets for fire/smoke, which is faster than ray marching. Ray-marched volumes are used in offline rendering (films, VFX) and cinematic-quality game cutscenes.- **Three.js `FogExp2`**: for simple atmosphere, Three.js's built-in exponential fog is computationally free (depth-based fog applied in the vertex shader). Use volumetric ray marching only when fog must have specific 3D shape.diff --git a/animations/06-3d-advanced/volumetric-smoke/index.html b/animations/06-3d-advanced/volumetric-smoke/index.htmlindex 196bbb7c..ecfca335 100644--- a/animations/06-3d-advanced/volumetric-smoke/index.html+++ b/animations/06-3d-advanced/volumetric-smoke/index.html@@ -34,6 +34,8 @@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}+ .msg{position:absolute;inset:0;display:none;align-items:center;justify-content:center;text-align:center;padding:24px;font-size:11px;color:var(--ui-muted);line-height:1.7;white-space:pre-wrap}+ .msg.on{display:flex}.src-panel{position:absolute;bottom:0;left:0;right:0;background:rgba(11,11,13,.92);border-top:1px solid var(--ui-border);padding:12px;font-size:8.5px;color:var(--ui-muted);font-family:var(--mono);line-height:1.5;max-height:220px;overflow-y:auto;display:none;white-space:pre-wrap;word-break:break-all}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}@@ -77,6 +79,7 @@ body{padding-top:46px}<div class="badge" id="fps">— fps</div><div class="badge" id="steps-badge">32 steps</div></div>+ <div class="msg" id="msg"></div><div class="src-panel" id="src-panel"></div></div><aside>@@ -101,7 +104,11 @@ body{padding-top:46px}<script>const VS=`attribute vec2 a;void main(){gl_Position=vec4(a,0.,1.);}`;const FS=`+#ifdef GL_FRAGMENT_PRECISION_HIGH+precision highp float;+#elseprecision mediump float;+#endifuniform vec2 uRes;uniform float uT,uDens,uSpd;uniform int uSteps;uniform bool uWind,uDither;uniform vec3 uSmoke,uBG;@@ -124,22 +131,22 @@ float density(vec3 p,float t){float windX=uWind?t*.08:0.;vec3 q=p+vec3(windX,0.,0.);// Cone source shape: narrower at top- float r=length(p.xz);float src=exp(-r*3.)*smoothstep(-.2,0.6,p.y)*smoothstep(1.8,1.0,p.y);+ float r=length(p.xz);float src=exp(-r*3.)*smoothstep(-.2,0.6,p.y)*(1.-smoothstep(1.0,1.8,p.y));float n=fbm(q*1.4+vec3(0.,t*uSpd*.4,0.));return max(0.,n-.45)*src*uDens*2.;}float dither(vec2 co){- return (fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5)-.5)*.02;+ return fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5)-.5;}void main(){vec2 uv=(gl_FragCoord.xy-.5*uRes)/min(uRes.x,uRes.y);vec3 ro=vec3(0.,0.,3.);vec3 rd=normalize(vec3(uv,-.9));- vec3 col=uBG;+ vec3 col=vec3(0.);float transmit=1.,stepSz=3./float(uSteps);- float tStart=uDither?dither(gl_FragCoord.xy):0.;+ float tStart=uDither?dither(gl_FragCoord.xy)*stepSz:0.;vec3 lightDir=normalize(vec3(1.5,2.,1.));float t=.2+tStart;for(int i=0;i<96;i++){@@ -168,23 +175,39 @@ void main(){const stage=document.getElementById('stage'),cvs=document.getElementById('cvs');const fpsEl=document.getElementById('fps'),stepsBadge=document.getElementById('steps-badge');-const srcPanel=document.getElementById('src-panel');+const srcPanel=document.getElementById('src-panel'),msgEl=document.getElementById('msg');+const stepsSl=document.getElementById('steps-sl');let W,H,gl,prog,raf=null,paused=false,lastT=0,startT=0,pausedAt=0,curT=2;let DENS=0.7,SPD=0.6,STEPS=32,WIND=true,DITHER=true;let SMOKE=[154/255,180/255,216/255],BG=[3/255,8/255,16/255];function h2r(h){return[parseInt(h.slice(1,3),16)/255,parseInt(h.slice(3,5),16)/255,parseInt(h.slice(5,7),16)/255];}+function fail(msg){msgEl.textContent=msg;msgEl.classList.add('on');fpsEl.textContent='—';}function init(){gl=cvs.getContext('webgl');if(!gl)return false;- function sh(t,s){const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);if(!gl.getShaderParameter(x,gl.COMPILE_STATUS))console.error(gl.getShaderInfoLog(x));return x;}+ let glErr='';+ function sh(t,s){const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);if(!gl.getShaderParameter(x,gl.COMPILE_STATUS)){glErr=(gl.getShaderInfoLog(x)||'shader compile failed').replace(/\0/g,'').trim();console.error(glErr);}return x;}prog=gl.createProgram();gl.attachShader(prog,sh(gl.VERTEX_SHADER,VS));gl.attachShader(prog,sh(gl.FRAGMENT_SHADER,FS));gl.linkProgram(prog);- if(!gl.getProgramParameter(prog,gl.LINK_STATUS))console.error(gl.getProgramInfoLog(prog));+ if(!gl.getProgramParameter(prog,gl.LINK_STATUS)){const e=(gl.getProgramInfoLog(prog)||'program link failed').replace(/\0/g,'').trim();console.error(e);if(!glErr)glErr=e;}+ // A failed compile otherwise draws nothing at all, with no visible symptom.+ if(glErr){fail('Shader failed to build: '+glErr);return false;}const buf=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,buf);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),gl.STATIC_DRAW);const a=gl.getAttribLocation(prog,'a');gl.enableVertexAttribArray(a);gl.vertexAttribPointer(a,2,gl.FLOAT,false,0,0);srcPanel.textContent=FS;return true;}-function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;if(gl){gl.viewport(0,0,W,H);refresh();}}+function setSteps(n){STEPS=n;stepsSl.value=n;document.getElementById('steps-v').textContent=n;stepsBadge.textContent=n+' steps';}+// Ray marching is fill-rate bound, so the backing store never exceeds one CSS+// pixel per fragment. Phones render below that and cap the march steps as well+// — that pair is the reduced-quality path this effect needs on mobile.+function quality(){const mob=innerWidth<=600;return{scale:Math.min(devicePixelRatio||1,mob?.75:1),maxSteps:mob?48:96};}+function resize(){+ const q=quality();+ W=cvs.width=Math.max(1,Math.round(stage.clientWidth*q.scale));+ H=cvs.height=Math.max(1,Math.round(stage.clientHeight*q.scale));+ if(+stepsSl.max!==q.maxSteps){stepsSl.max=q.maxSteps;if(STEPS>q.maxSteps)setSteps(q.maxSteps);}+ if(gl){gl.viewport(0,0,W,H);refresh();}+}function u(n){return gl.getUniformLocation(prog,n);}// Resizing clears the canvas and control changes need a frame: redraw while pausedfunction refresh(){if(paused&&gl)draw(curT);}@@ -210,14 +233,15 @@ function draw(t){const pauseBtn=document.getElementById('pause-btn');if(init()){resize();startT=performance.now();lastT=startT;window.addEventListener('resize',resize);+ cvs.addEventListener('webglcontextlost',e=>{e.preventDefault();paused=true;cancelAnimationFrame(raf);raf=null;fail('WebGL context lost — reload the page to restart the render.');});if(matchMedia('(prefers-reduced-motion: reduce)').matches){paused=true;pausedAt=startT;pauseBtn.textContent='▶ Resume';fpsEl.textContent='static';draw(curT);}else raf=requestAnimationFrame(render);-}else fpsEl.textContent='WebGL unavailable';+}else if(!gl)fail('WebGL is unavailable in this browser, so the volume cannot be ray marched.');document.getElementById('dens-sl').addEventListener('input',e=>{DENS=e.target.value/10;document.getElementById('dens-v').textContent=DENS.toFixed(1);refresh();});-document.getElementById('spd-sl').addEventListener('input',e=>{SPD=e.target.value/10;document.getElementById('spd-v').textContent=SPD.toFixed(1);});-document.getElementById('steps-sl').addEventListener('input',e=>{STEPS=+e.target.value;document.getElementById('steps-v').textContent=STEPS;stepsBadge.textContent=STEPS+' steps';refresh();});+document.getElementById('spd-sl').addEventListener('input',e=>{SPD=e.target.value/10;document.getElementById('spd-v').textContent=SPD.toFixed(1);refresh();});+stepsSl.addEventListener('input',e=>{setSteps(+e.target.value);refresh();});document.getElementById('smoke-pick').addEventListener('input',e=>{SMOKE=h2r(e.target.value);refresh();});document.getElementById('bg-pick').addEventListener('input',e=>{BG=h2r(e.target.value);refresh();});document.getElementById('wind-tog').addEventListener('change',e=>{WIND=e.target.checked;refresh();});diff --git a/animations/06-3d-advanced/webgl-shader-animation/README.md b/animations/06-3d-advanced/webgl-shader-animation/README.mdindex 34f401ee..b0ae3dc0 100644--- a/animations/06-3d-advanced/webgl-shader-animation/README.md+++ b/animations/06-3d-advanced/webgl-shader-animation/README.md@@ -66,9 +66,13 @@ float voronoi(vec2 p) {|-----------|---------|--------|| Time speed | 1.0× | Multiplier on `uT` uniform — faster = more energetic animation || Hue shift | 0° | Rotates the entire color palette without rewriting the shader |-| Max steps (where applicable) | — | Quality/performance tradeoff in iterative shaders |+| Mouse interaction | off | Feeds a normalised `M` uniform into the shader — each preset uses it differently |+| Device pixel ratio | ≤2 (≤1.5 on mobile) | Backing-store multiplier. Capped, because fill cost scales with its square |## Production notes+- **Always check `COMPILE_STATUS` and `LINK_STATUS`.** A shader that fails to compile throws nothing and logs nothing — `gl.drawArrays` just quietly draws nothing and you get a black canvas. Read `getShaderInfoLog` / `getProgramInfoLog` and put the message somewhere a human will see it. This demo renders the compile log into the stage; break a shader on purpose and you get the GLSL error, not a black box.+- **Handle context loss.** `webglcontextlost` fires on a GPU reset, a driver update, or a backgrounded tab that the OS reclaims. Call `preventDefault()` on it — otherwise the context never comes back — then rebuild buffers, programs and uniform locations in `webglcontextrestored`. Every GL object from the old context is gone.+- **Size the backing store in device pixels**, not CSS pixels: `canvas.width = clientWidth * dpr`. Then update `gl.viewport(0, 0, canvas.width, canvas.height)` in the same place — forgetting the viewport is the classic resize bug, and it stretches or crops the scene instead of failing loudly.- **Shadertoy**: all four patterns in this demo are canonical Shadertoy exercises. The site has a live GLSL editor, a large library of community shaders, and a standard uniform convention (`iTime`, `iResolution`, `iMouse`).- **Canvas resolution**: shader cost scales with pixel count. At 4K, a complex shader runs 4× slower than at 1080p. Use `devicePixelRatio` carefully — rendering at 0.5× device pixels and upscaling often looks fine for background shaders.- **`mediump` vs `highp`**: `precision mediump float` is required on mobile. Some shaders produce visible banding at `mediump` — switch to `precision highp float` for patterns with fine detail.diff --git a/animations/06-3d-advanced/webgl-shader-animation/index.html b/animations/06-3d-advanced/webgl-shader-animation/index.htmlindex b84b2204..56cd8922 100644--- a/animations/06-3d-advanced/webgl-shader-animation/index.html+++ b/animations/06-3d-advanced/webgl-shader-animation/index.html@@ -36,6 +36,8 @@.fps-badge{font-size:9px;color:rgba(255,255,255,.5);background:rgba(0,0,0,.4);padding:3px 8px;border-radius:4px}.shader-name{font-size:9px;color:rgba(255,255,255,.6);background:rgba(0,0,0,.4);padding:3px 10px;border-radius:4px;letter-spacing:1px;text-transform:uppercase}.src-panel{position:absolute;bottom:0;left:0;right:0;background:rgba(11,11,13,.9);border-top:1px solid var(--ui-border);padding:12px;font-size:9px;color:var(--ui-muted);font-family:var(--mono);line-height:1.5;max-height:200px;overflow-y:auto;display:none;white-space:pre-wrap;word-break:break-all}+ .gl-msg{position:absolute;inset:0;display:none;align-items:center;justify-content:center;text-align:center;padding:clamp(16px,4vw,32px);background:var(--bg);color:var(--ui-text);font-size:clamp(10px,2.2vw,12px);line-height:1.7;white-space:pre-wrap;overflow-y:auto}+ .gl-msg.on{display:flex}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)}@@ -78,6 +80,7 @@ body{padding-top:46px}<div class="shader-name" id="shader-name">Plasma</div></div><div class="src-panel" id="src-panel"></div>+ <div class="gl-msg" id="gl-msg" role="status"></div></div><aside><p class="note">Fragment shaders run once per pixel on the GPU. The boilerplate (vertex shader, quad geometry, uniforms) stays identical — only the fragment shader changes per preset.</p>@@ -95,7 +98,7 @@ body{padding-top:46px}<label class="tog"><input type="checkbox" id="mouse-tog"><span>Mouse interaction</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>+ <button type="button" class="rst" id="pause-btn">⏸ Pause</button></aside></div><script>@@ -104,21 +107,23 @@ const VS=`attribute vec2 a;void main(){gl_Position=vec4(a,0.,1.);}`;const SHADERS=[// 0: Plasma{name:'Plasma',src:`precision mediump float;-uniform vec2 R;uniform float T,H;+uniform vec2 R,M;uniform float T,H;uniform bool uMouse;vec3 hsv(float h,float s,float v){vec4 K=vec4(1.,2./3.,1./3.,3.);vec3 p=abs(fract(vec3(h)+K.xyz)*6.-K.www);return v*mix(K.xxx,clamp(p-K.xxx,0.,1.),s);}void main(){vec2 uv=gl_FragCoord.xy/R*2.-1.;uv.x*=R.x/R.y;- float v=sin(uv.x*5.+T)+sin(uv.y*5.+T*.7)+sin((uv.x+uv.y)*5.+T*.5)+sin(sqrt(uv.x*uv.x+uv.y*uv.y)*6.);+ vec2 c=vec2(0.);if(uMouse)c=(M*2.-1.)*vec2(R.x/R.y,1.);+ float v=sin(uv.x*5.+T)+sin(uv.y*5.+T*.7)+sin((uv.x+uv.y)*5.+T*.5)+sin(length(uv-c)*6.);float hue=fract(v*.25+T*.05+H/360.);gl_FragColor=vec4(hsv(hue,.9,.95),1.);}`},// 1: Wave distortion{name:'Wave Distortion',src:`precision mediump float;-uniform vec2 R;uniform float T,H;+uniform vec2 R,M;uniform float T,H;uniform bool uMouse;vec3 hsv(float h,float s,float v){vec4 K=vec4(1.,2./3.,1./3.,3.);vec3 p=abs(fract(vec3(h)+K.xyz)*6.-K.www);return v*mix(K.xxx,clamp(p-K.xxx,0.,1.),s);}void main(){vec2 uv=gl_FragCoord.xy/R;float wave=sin(uv.y*12.+T*2.)*.04+sin(uv.x*8.-T*1.5)*.03;+ if(uMouse)wave*=1.+4.*exp(-14.*dot(uv-M,uv-M));vec2 d=uv+vec2(wave,wave*1.3);float stripe=sin(d.x*20.+T)*sin(d.y*20.-T*.6);float hue=fract(stripe*.3+H/360.+T*.02);@@ -126,11 +131,13 @@ void main(){}`},// 2: Voronoi{name:'Voronoi',src:`precision mediump float;-uniform vec2 R;uniform float T,H;+uniform vec2 R,M;uniform float T,H;uniform bool uMouse;vec3 hsv(float h,float s,float v){vec4 K=vec4(1.,2./3.,1./3.,3.);vec3 p=abs(fract(vec3(h)+K.xyz)*6.-K.www);return v*mix(K.xxx,clamp(p-K.xxx,0.,1.),s);}float rand(vec2 p){return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5);}void main(){- vec2 uv=gl_FragCoord.xy/R*4.;+ vec2 q=gl_FragCoord.xy/R;+ if(uMouse){vec2 dm=q-M;q+=dm*.7*exp(-16.*dot(dm,dm));}+ vec2 uv=q*4.;vec2 i=floor(uv),f=fract(uv);float md=8.,mi=0.;for(int y=-1;y<=1;y++)for(int x=-1;x<=1;x++){@@ -161,51 +168,82 @@ void main(){const stage=document.getElementById('stage');const cvs=document.getElementById('cvs');const fpsEl=document.getElementById('fps');const shaderName=document.getElementById('shader-name');const srcPanel=document.getElementById('src-panel');-const pauseBtn=document.getElementById('pause-btn');-let W,H,gl,prog=null,raf=null,paused=false,lastT=0,T=0;+const pauseBtn=document.getElementById('pause-btn');const msgEl=document.getElementById('gl-msg');+let W,H,gl,prog=null,U=null,raf=null,paused=false,lastT=0,T=0;let PRESET=0,SPD=1,HUE=0,MOUSE_UV=[.5,.5],MOUSE_ON=false;+// A failed shader is otherwise invisible: the canvas just stays black.+function fail(msg){msgEl.textContent=msg;msgEl.classList.add('on');cvs.style.visibility='hidden';fpsEl.textContent='—';}+function clearFail(){msgEl.classList.remove('on');msgEl.textContent='';cvs.style.visibility='';}+function mkProg(fs){- function sh(t,s){const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);return x;}- const p=gl.createProgram();- gl.attachShader(p,sh(gl.VERTEX_SHADER,VS));- gl.attachShader(p,sh(gl.FRAGMENT_SHADER,fs));- gl.linkProgram(p);return p;+ function sh(t,s){+ const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);+ if(!gl.getShaderParameter(x,gl.COMPILE_STATUS)){+ const log=gl.getShaderInfoLog(x);gl.deleteShader(x);+ throw new Error((t===gl.VERTEX_SHADER?'Vertex':'Fragment')+' shader failed to compile:\n'+log);+ }+ return x;+ }+ const p=gl.createProgram(),v=sh(gl.VERTEX_SHADER,VS),f=sh(gl.FRAGMENT_SHADER,fs);+ gl.attachShader(p,v);gl.attachShader(p,f);gl.linkProgram(p);+ gl.deleteShader(v);gl.deleteShader(f);+ if(!gl.getProgramParameter(p,gl.LINK_STATUS)){+ const log=gl.getProgramInfoLog(p);gl.deleteProgram(p);+ throw new Error('Program failed to link:\n'+log);+ }+ return p;}function init(){gl=cvs.getContext('webgl');if(!gl)return false;const buf=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,buf);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),gl.STATIC_DRAW);- switchShader(0);return true;+ switchShader(PRESET);return true;}function switchShader(idx){PRESET=idx;+ shaderName.textContent=SHADERS[idx].name;+ if(document.getElementById('src-tog').checked)srcPanel.textContent=SHADERS[idx].src;if(!gl)return;+ let next;+ try{next=mkProg(SHADERS[idx].src);}+ catch(err){+ if(raf!==null){cancelAnimationFrame(raf);raf=null;}+ prog=null;U=null;+ fail(SHADERS[idx].name+' shader did not build.\n\n'+err.message);+ return;+ }if(prog)gl.deleteProgram(prog);- prog=mkProg(SHADERS[idx].src);+ prog=next;clearFail();+ gl.useProgram(prog);+ U={};['R','T','H','M','uMouse'].forEach(n=>{U[n]=gl.getUniformLocation(prog,n);});const a=gl.getAttribLocation(prog,'a');gl.enableVertexAttribArray(a);gl.vertexAttribPointer(a,2,gl.FLOAT,false,0,0);- shaderName.textContent=SHADERS[idx].name;- if(document.getElementById('src-tog').checked)srcPanel.textContent=SHADERS[idx].src;}-function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;if(gl){gl.viewport(0,0,W,H);still();}}+// Render at device pixels so the shader is not upscaled from a smaller buffer.+// Capped — and capped harder on phones, where a full 3x buffer is 9x the fill cost.+function resize(){+ const dpr=Math.min(window.devicePixelRatio||1,innerWidth<=600?1.5:2);+ W=cvs.width=Math.max(1,Math.round(stage.clientWidth*dpr));+ H=cvs.height=Math.max(1,Math.round(stage.clientHeight*dpr));+ if(gl){gl.viewport(0,0,W,H);still();}+}function draw(){gl.useProgram(prog);- const u=n=>gl.getUniformLocation(prog,n);- gl.uniform2f(u('R'),W,H);gl.uniform1f(u('T'),T);gl.uniform1f(u('H'),HUE);- if(MOUSE_ON){gl.uniform2f(u('M'),MOUSE_UV[0],MOUSE_UV[1]);gl.uniform1i(u('uMouse'),1);}- else gl.uniform1i(u('uMouse'),0);+ gl.uniform2f(U.R,W,H);gl.uniform1f(U.T,T);gl.uniform1f(U.H,HUE);+ if(MOUSE_ON){gl.uniform2f(U.M,MOUSE_UV[0],MOUSE_UV[1]);gl.uniform1i(U.uMouse,1);}+ else gl.uniform1i(U.uMouse,0);gl.drawArrays(gl.TRIANGLE_STRIP,0,4);}// Redraw the held frame while paused so controls still take effect.function still(){if(paused&&prog)draw();}function render(ts){- if(paused){raf=null;return;}+ if(paused||!prog){raf=null;return;}raf=requestAnimationFrame(render);const dt=ts-lastT;if(dt<16)return;fpsEl.textContent=Math.round(1000/(dt||16))+' fps';lastT=ts;@@ -216,17 +254,31 @@ function render(ts){function setPaused(p){paused=p;pauseBtn.textContent=paused?'▶ Resume':'⏸ Pause';if(paused){cancelAnimationFrame(raf);raf=null;still();}- else if(gl&&raf===null){lastT=performance.now();raf=requestAnimationFrame(render);}+ else if(gl&&prog&&raf===null){lastT=performance.now();raf=requestAnimationFrame(render);}}if(init()){resize();if(matchMedia('(prefers-reduced-motion:reduce)').matches)setPaused(true);else{lastT=performance.now();raf=requestAnimationFrame(render);}- stage.addEventListener('pointermove',e=>{const r=cvs.getBoundingClientRect();MOUSE_UV=[(e.clientX-r.left)/r.width,(e.clientY-r.top)/r.height];still();});+ // Pointer Events, so the same handler serves mouse, pen and touch.+ // y is flipped because gl_FragCoord counts from the bottom of the buffer.+ stage.addEventListener('pointermove',e=>{const r=cvs.getBoundingClientRect();MOUSE_UV=[(e.clientX-r.left)/r.width,1-(e.clientY-r.top)/r.height];still();});window.addEventListener('resize',resize);+ // A GPU reset or a restored tab kills the context; without this the demo dies for good.+ cvs.addEventListener('webglcontextlost',e=>{+ e.preventDefault();+ if(raf!==null){cancelAnimationFrame(raf);raf=null;}+ prog=null;U=null;fail('WebGL context lost. Waiting for the browser to restore it…');+ });+ cvs.addEventListener('webglcontextrestored',()=>{+ if(!init())return;+ clearFail();resize();+ if(!paused&&raf===null){lastT=performance.now();raf=requestAnimationFrame(render);}+ });}else{- cvs.style.display='none';fpsEl.textContent='WebGL is not available in this browser';+ fail('WebGL is not available in this browser.\n\nThis demo needs a WebGL 1.0 context — the patterns are generated by fragment shaders on the GPU, so there is nothing to fall back to. Try a different browser, or enable hardware acceleration.');+ document.querySelectorAll('aside select,aside input,aside button').forEach(el=>{el.disabled=true;});}document.getElementById('preset-sel').addEventListener('change',e=>{switchShader(+e.target.value);still();});