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: Cloth Simulation steps in fixed 1/60 s sub-steps from an accumulator, so it falls and swings at the same speed on every screen
matin84fe3e9ef76e
diff --git a/animations/06-3d-advanced/cloth-simulation/README.md b/animations/06-3d-advanced/cloth-simulation/README.mdindex 0425d7aa..1fc09e0f 100644--- a/animations/06-3d-advanced/cloth-simulation/README.md+++ b/animations/06-3d-advanced/cloth-simulation/README.md@@ -1,7 +1,7 @@# Cloth / Soft-Body Simulation## What it is-A cloth simulation treats fabric as a grid of points joined by links of fixed length. Each frame, every point keeps moving the way it was moving, plus gravity and wind, and then the links pull neighbouring points back into shape. Pin a few points and the grid hangs, sways and folds like fabric, and you can grab it.+A cloth simulation treats fabric as a grid of points joined by links of fixed length. Sixty times a second, every point keeps moving the way it was moving, plus gravity and wind, and then the links pull neighbouring points back into shape. Pin a few points and the grid hangs, sways and folds like fabric, and you can grab it.## When to use it- Animated flags and banners on hero sections@@ -10,7 +10,7 @@ A cloth simulation treats fabric as a grid of points joined by links of fixed le- Educational demonstrations of physics simulation in the browser## How it works-**Verlet integration** — each vertex updates using its own history:+**Verlet integration** — each vertex updates using its own history (`dt` is the fixed step, 1/60 s):```jsfunction integrate(dt) {@@ -46,6 +46,25 @@ function solveConstraints(iterations) {}```+**Fixed steps** — Verlet keeps a point's velocity as the distance it moved in the last step, so every step must be the same length. Scaling one step by the time since the last frame changes the physics, and a long step throws points further than the links can pull them back. The demo therefore always steps by 1/60 s and runs as many steps per drawn frame as the time since the last frame calls for:++```js+const STEP = 1000 / 60; // one physics step, in milliseconds+let behind = 0; // time that has passed but not been stepped yet++function frame(elapsed) { // elapsed: ms since the last drawn frame+ behind += Math.min(elapsed, 50); // a long gap counts for at most 50 ms+ for (let n = 0; behind >= STEP - 1 && n < 3; n++) { // 1 ms of slack, at most 3 steps+ integrate();+ solveConstraints(iterations);+ behind -= STEP;+ }+ draw();+}+```++A 60 Hz screen runs one step per frame, a 30 Hz screen two, and a 144 Hz screen one step every two or three frames, so the cloth falls and swings at the same speed on every one of them. The 1 ms of slack keeps a frame that arrives a hair early from being skipped and then paid for twice, and the cap of three steps means a device that cannot keep up makes the cloth slower instead of piling up more work.+**Rendering** — the triangulated mesh is drawn as filled quads. Each quad is split into two triangles sharing the diagonal:```js@@ -64,18 +83,19 @@ for (let r = 0; r < ROWS; r++) {|-----------|---------|--------|| Hangs from | Two corners | Pins the top two corners, the whole top edge, one corner, or nothing, in which case the cloth falls to the floor || Wind | Medium | How hard the wind blows; it rises and falls on its own: light is 0.2, medium 0.5 and strong 1.2 |-| Stiffness | Medium | How many times each frame the links are pulled back to length: stretchy is 2, medium 4 and stiff 8 |+| Stiffness | Medium | How many times each step, sixty a second, the links are pulled back to length: stretchy is 2, medium 4 and stiff 8 || Gravity | Normal | How heavy the cloth is: light is 0.06, normal 0.12 and heavy 0.2 || Detail | Medium | How many points the cloth has: low is 16 × 12, medium 24 × 18 and high 40 × 30; phones start at low || Shows the points | off | Marks every point of the grid, with the pinned ones in red |## Production notes-- **Verlet vs explicit Euler**: explicit Euler integration stores velocity explicitly and adds it to position each frame. Verlet integration is more numerically stable for constrained systems — cloth springs don't "explode" as easily at large time steps.+- **Verlet vs explicit Euler**: explicit Euler integration stores velocity explicitly and adds it to position on every step. Verlet integration is more numerically stable for constrained systems — cloth springs don't "explode" as easily at large time steps.+- **Fixed time step**: one step per drawn frame makes the cloth fall twice as fast on a 120 Hz screen and half as fast on a 30 Hz phone, and stretching a step to the length of the frame changes what Verlet computes. Step by a fixed 1/60 s from an accumulator, as above, and draw once per frame.- **Bending constraints**: for realistic cloth, add shear constraints (diagonal neighbors) and bending constraints (one vertex apart). This demo uses structural constraints only (immediate neighbors) for simplicity.- **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 (1,271 points, 2,470 links, 4 passes = 9,880 link corrections a frame) a phone-class CPU manages about 17 frames a second, and 24×18 about 47. The demo starts at 16×12 on phones (screens 600px wide or less, or 500px tall or less), where it holds 60; its Detail setting still lets you pick more.+- **Performance**: at 40×30 (1,271 points, 2,470 links, 4 passes = 9,880 link corrections a step) a phone-class CPU manages about 17 frames a second (one step and one drawing each), and 24×18 about 47. The demo starts at 16×12 on phones (screens 600px wide or less, or 500px tall or less), where it holds 60; its Detail setting still lets you pick more.- **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 alsodiff --git a/animations/06-3d-advanced/cloth-simulation/index.html b/animations/06-3d-advanced/cloth-simulation/index.htmlindex 05494ef9..e133b072 100644--- a/animations/06-3d-advanced/cloth-simulation/index.html+++ b/animations/06-3d-advanced/cloth-simulation/index.html@@ -125,7 +125,7 @@<div><h2 id="hb-prompt-title">Copy the prompt</h2><p>Paste it into an AI assistant such as ChatGPT, Claude or Cursor to build this in your own project.</p></div></div><div class="hb-card">- <p class="hb-prompt">Add a cloth simulation to [the flag, banner or fabric you want to show]. Model the cloth as a grid of points joined to their neighbours by links of fixed length. Each frame, move every point by its own momentum plus gravity and wind, then pull linked points back toward their proper distance a few times over. Pin some points so the cloth hangs, and let the visitor grab and drag the nearest point with the pointer or a finger. Use a coarser grid on phones. If the visitor has reduced motion turned on, show the cloth hanging still. Match the settings listed below.</p>+ <p class="hb-prompt">Add a cloth simulation to [the flag, banner or fabric you want to show]. Model the cloth as a grid of points joined to their neighbours by links of fixed length. In fixed 1/60 s steps, as many as the time since the last frame needs, move every point by its own momentum plus gravity and wind, then pull linked points back toward their proper distance a few times over, so the cloth moves at the same speed on every screen. Pin some points so the cloth hangs, and let the visitor grab and drag the nearest point with the pointer or a finger. Use a coarser grid on phones. If the visitor has reduced motion turned on, show the cloth hanging still. Match the settings listed below.</p><div class="hb-chips-box" hidden><p class="hb-chips-title">Your settings</p><ul class="hb-chips"></ul>@@ -159,7 +159,7 @@<script>const cvs=document.getElementById('cvs'),ctx=cvs.getContext('2d');const stage=document.getElementById('stage');-let W,H,paused=false,raf=null,lastT=0,windT=0;+let W,H,paused=false,raf=null,lastT=null,windT=0,behind=0;let COLS=24,ROWS=18,GRAVITY=0.12,WIND=0.5,ITERS=4,PIN_MODE='top-corners';let SHOW_VERTS=false;let pts=[],prev=[],pinned=[],constraints=[];@@ -267,19 +267,31 @@ function draw(){}}-// The loop keeps exactly one pending frame in raf. Each drawn frame is one physics step. The wind follows the page's own-// clock, which adds up the time of each drawn frame (at most 50 ms), so a pause never makes the wind jump.+// Verlet keeps a point's speed as the distance it moved in the last step, so every step must be the same length, or the+// cloth's physics change with it (and one long step throws the points further than the links can pull them back). The loop+// therefore always steps by 1/60 s (FRAME) and runs as many steps as the time since the last drawn frame calls for: one on a+// 60 Hz screen, two on a 30 Hz one. "behind" is the time not yet stepped; 1 ms of slack keeps a frame that comes a hair early+// from being skipped and paid for twice. A long gap counts for at most 50 ms and a frame runs at most 3 steps, so a slow+// device makes the cloth slower instead of piling up more work. At most one picture is drawn per 16 ms.+const FRAME=1000/60;+// The loop keeps exactly one pending frame in raf. The wind follows the page's own clock, which adds up the steps taken, so a+// pause never makes the wind jump.function loop(ts){raf=requestAnimationFrame(loop);+ if(lastT===null){lastT=ts;return;} // the first frame after a start only takes the timeconst dt=ts-lastT;if(dt<16)return;lastT=ts;- windT+=Math.min(dt,50);- update();draw();+ behind+=Math.min(dt,50);+ let steps=0;+ while(behind>=FRAME-1&&steps<3){windT+=FRAME;update();behind-=FRAME;steps++;}+ if(steps)draw();}// Hangs a fresh cloth to the size of the stage (Detail, a resize) ...function rebuild(settle){resize();initCloth(settle);}// ... and Play carries on with the cloth as it is; it never stacks a second loop.-function resume(){if(raf!==null)return;lastT=performance.now();raf=requestAnimationFrame(loop);}+function resume(){if(raf!==null)return;lastT=null;behind=0;raf=requestAnimationFrame(loop);}+// A tab that comes back to the front starts again from its next frame, so the time away adds no step.+document.addEventListener('visibilitychange',()=>{lastT=null;behind=0;});// Registered at the top level, before the shared script (deferred) can run: under reduced motion it pauses the// loop on arrival, which this listener must catch. Pause cancels the pending frame and the cloth stays where it is.