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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cloth / Soft-Body Simulation — Animation Handbook</title>
<meta name="description" content="A cloth sways in the wind, and you can drag it around. Best for playful pages.">
<link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/cloth-simulation/">
<link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png">
<link rel="icon" type="image/svg+xml" href="../../../favicon.svg">
<link rel="apple-touch-icon" href="../../../apple-touch-icon.png">
<meta property="og:type" content="article">
<meta property="og:site_name" content="Animation Handbook">
<meta property="og:title" content="Cloth / Soft-Body Simulation — Animation Handbook">
<meta property="og:description" content="A cloth sways in the wind, and you can drag it around. Best for playful pages.">
<meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/cloth-simulation/">
<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="Cloth / Soft-Body Simulation — Animation Handbook">
<meta name="twitter:description" content="A cloth sways in the wind, and you can drag it around. Best for playful pages.">
<meta name="twitter:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
<script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "Cloth / Soft-Body Simulation", "name": "Cloth / Soft-Body Simulation", "description": "A cloth sways in the wind, and you can drag it around. Best for playful pages.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/cloth-simulation/", "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, Cloth / Soft-Body Simulation"}</script>
<style>
:root{--ui-accent:#3fd6c4}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
.stage{position:relative;background:#0b0b0d;touch-action:none}
canvas{display:block;width:100%;height:100%;touch-action:none;cursor:grab}
/* See inside and Compare: plain words over the canvas. See inside's key sits bottom right, where the gold links seldom are (top right when nothing is pinned and the cloth
is falling to the floor), with a small canvas of its own for the two pushes. */
.key,.half{display:none}
.stage[data-hb-mode="inside"] .key{display:flex}
.stage[data-hb-mode="compare"] .half{display:block}
.lbl{color:#f4f4f2;font:600 13px/1.25 var(--hb-font);white-space:nowrap;pointer-events:none}
.key{position:absolute;right:10px;bottom:10px;flex-direction:column;align-items:flex-start;gap:5px;padding:8px 12px;border:1px solid rgba(255,255,255,.1);border-radius:8px;background:rgba(11,11,13,.88);pointer-events:none}
.key.top{bottom:auto;top:10px}.key.nopin .red{display:none}.key.still .pts{display:none}.key.still{bottom:6px}
.k{display:flex;align-items:center}
.k::before{content:"";flex:none;width:16px;height:2px;margin-right:8px;background:#e8ebf2}
.k.gold::before{height:3px;background:#f4b942}
.k.red::before{width:8px;height:8px;margin:0 12px 0 4px;border-radius:50%;background:#f85149;box-shadow:0 0 0 2px #161618,0 0 0 3.5px #f85149}
.push{position:relative;width:150px;height:52px}.push canvas{position:absolute;inset:0}
.push .lbl{position:absolute;left:calc(34% + 10px)}.wind{top:0}.grav{top:29px}
.half{position:absolute;top:6px;transform:translateX(-50%);padding:2px 9px;border-radius:999px;background:rgba(11,11,13,.88)}
.half.first{left:25%}.half.second{left:75%}
/* Phones and short stages: a smaller key, so it covers less of a cloth that hangs low */
@media(max-width:600px),(max-height:660px){.key{gap:4px;padding:6px 10px}.k.pts{display:none}.k{max-width:200px;white-space:normal;text-wrap:balance}}
@media(max-width:600px){.lbl{font-size:12px}}
</style>
<link rel="stylesheet" href="../../../assets/css/demo-page.css?v=11">
<script src="../../../assets/js/demo-page.js?v=11" defer></script>
</head>
<body class="hb" data-hb-kind="loop">
<nav class="hb-bar" aria-label="Animation Handbook">
<a class="hb-home" href="../../../"><svg class="hb-mark" viewBox="0 0 32 32" aria-hidden="true"><g class="g"><circle cx="11.16" cy="20.84" r="6.1"/><circle cx="15.12" cy="16.88" r="6.1"/><circle cx="18.51" cy="13.49" r="6.1"/></g><circle class="b" cx="21.2" cy="10.8" r="6.6"/></svg><span>Animation Handbook</span></a>
<span class="hb-pager"><a href="../image-distortion-hover/" rel="prev" aria-label="Previous: Image Distortion on Hover"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg><span><span class="hb-dir">Previous: </span>Image Distortion on Hover</span></a><a href="../volumetric-smoke/" rel="next" aria-label="Next: Volumetric Smoke / 3D Noise"><span><span class="hb-dir">Next: </span>Volumetric Smoke / 3D Noise</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m9 18 6-6-6-6"/></svg></a></span>
<a class="hb-star" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener" aria-label="Star on GitHub"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg><span>Star on GitHub</span></a>
</nav>
<main class="hb-page">
<header class="hb-head">
<p class="hb-cat">06.15 · 3D & Advanced</p>
<h1>Cloth / Soft-Body Simulation</h1>
<p class="hb-lede">A cloth sways in the wind, and you can drag it around. Best for playful pages.</p>
</header>
<section class="hb-step hb-watch" aria-labelledby="hb-watch-title">
<div class="hb-step-head">
<span class="hb-num" aria-hidden="true">1</span>
<div><h2 id="hb-watch-title">Watch it</h2><p>It moves by itself. Drag the cloth to pull it, or pause it to look closely.</p></div>
</div>
<div class="seg hb-modes" role="group" aria-label="What the box shows" data-hb-modes>
<button type="button" data-hb-mode="normal" class="on" aria-pressed="true">Normal</button>
<button type="button" data-hb-mode="inside" aria-pressed="false">See inside</button>
<button type="button" data-hb-mode="compare" aria-pressed="false">Compare</button>
</div>
<div class="stage" id="stage">
<canvas id="cvs" role="img" aria-label="A piece of cloth swaying in the wind, which you can drag with a pointer or a finger"></canvas>
<div class="key" aria-hidden="true">
<p class="lbl k pts" data-hb-caption>Points joined by links of fixed length</p>
<p class="lbl k gold" data-hb-caption>Gold: a stretched link pulls its points back</p>
<p class="lbl k red" data-hb-caption>Red: pinned, they never move</p>
<div class="push"><canvas></canvas><p class="lbl wind" data-hb-caption>Wind</p><p class="lbl grav" data-hb-caption>Gravity</p></div>
</div>
<p class="lbl half first" aria-hidden="true" data-hb-caption>No links</p>
<p class="lbl half second" aria-hidden="true" data-hb-caption>With links</p>
</div>
<div class="hb-player">
<button class="hb-play" type="button" id="btn-pause" data-hb-pause data-state="playing"><svg class="hb-ic hb-i-pause" viewBox="0 0 24 24" aria-hidden="true"><rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/></svg><svg class="hb-ic hb-i-play" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 3l14 9-14 9z"/></svg><span class="hb-pause-label">Pause</span></button>
<button class="hb-play" type="button" id="btn-reset" data-hb-reset><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/></svg>Reset</button>
</div>
<div class="hb-mode-notes" aria-live="polite">
<p data-hb-for="inside" hidden>Inside, the cloth is points joined by links: wind and gravity push every point, then each link pulls its two points back to its length (gold where stretched). Red points are pinned.</p>
<p data-hb-for="compare" hidden>No links: the same points, pushed by the same wind and gravity, fall away from their pins, since nothing holds them; With links: the cloth hangs and folds. Press Reset to hang both again.</p>
</div>
</section>
<section class="hb-step hb-try" aria-labelledby="hb-try-title">
<div class="hb-step-head">
<span class="hb-num" aria-hidden="true">2</span>
<div><h2 id="hb-try-title">Try it</h2><p>Change a setting and see the difference as it moves.</p></div>
</div>
<div class="hb-settings">
<div class="hb-setting">
<p class="hb-setting-name" id="pin-lbl">Hangs from</p>
<div class="seg" id="pin-seg" role="group" aria-labelledby="pin-lbl">
<button type="button" data-pin="top-corners" class="on" aria-pressed="true">Two corners</button>
<button type="button" data-pin="top-edge" aria-pressed="false">Top edge</button>
<button type="button" data-pin="single" aria-pressed="false">One corner</button>
<button type="button" data-pin="none" aria-pressed="false">Nothing</button>
</div>
<p class="hb-hint">Where the cloth is pinned; Nothing lets it fall.</p>
</div>
<div class="hb-setting">
<p class="hb-setting-name" id="wind-lbl">Wind</p>
<div class="seg" id="wind-seg" role="group" aria-labelledby="wind-lbl">
<button type="button" data-wind="0.2" aria-pressed="false">Light</button>
<button type="button" data-wind="0.5" class="on" aria-pressed="true">Medium</button>
<button type="button" data-wind="1.2" aria-pressed="false">Strong</button>
</div>
<p class="hb-hint">How hard the wind blows; it rises and falls.</p>
</div>
<div class="hb-setting">
<p class="hb-setting-name" id="stiff-lbl">Stiffness</p>
<div class="seg" id="stiff-seg" role="group" aria-labelledby="stiff-lbl">
<button type="button" data-iters="2" aria-pressed="false">Stretchy</button>
<button type="button" data-iters="4" class="on" aria-pressed="true">Medium</button>
<button type="button" data-iters="8" aria-pressed="false">Stiff</button>
</div>
<p class="hb-hint">Stretchy sags and bounces; stiff keeps its shape.</p>
</div>
</div>
<details class="hb-options">
<summary><span class="hb-more-label">More options</span><span class="hb-less">Fewer options</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg></summary>
<div class="hb-settings">
<div class="hb-setting">
<p class="hb-setting-name" id="grav-lbl">Gravity</p>
<div class="seg" id="grav-seg" role="group" aria-labelledby="grav-lbl">
<button type="button" data-grav="0.06" aria-pressed="false">Light</button>
<button type="button" data-grav="0.12" class="on" aria-pressed="true">Normal</button>
<button type="button" data-grav="0.2" aria-pressed="false">Heavy</button>
</div>
<p class="hb-hint">Heavy cloth hangs straighter and falls faster.</p>
</div>
<div class="hb-setting">
<p class="hb-setting-name" id="detail-lbl">Detail</p>
<div class="seg" id="detail-seg" role="group" aria-labelledby="detail-lbl">
<button type="button" data-cols="16" data-hb-phone aria-pressed="false">Low</button>
<button type="button" data-cols="24" class="on" aria-pressed="true">Medium</button>
<button type="button" data-cols="40" aria-pressed="false">High</button>
</div>
<p class="hb-hint">More points make finer folds; phones start at Low.</p>
</div>
<div class="hb-setting">
<label class="hb-switch-row"><span>Shows the points</span><input class="hb-switch" type="checkbox" role="switch" id="verts-tog" autocomplete="off"></label>
<p class="hb-hint">Marks each point; pinned ones are red.</p>
</div>
</div>
</details>
</section>
<section class="hb-step hb-prompt-step" aria-labelledby="hb-prompt-title">
<div class="hb-step-head">
<span class="hb-num" aria-hidden="true">3</span>
<div><h2 id="hb-prompt-title">Copy the prompt</h2><p>Paste it into an AI assistant such as ChatGPT, Claude or Cursor to build this in your own project.</p></div>
</div>
<div class="hb-card">
<p class="hb-prompt">Add a cloth simulation to [the flag, banner or fabric you want to show]. Model the cloth as a grid of points joined to their neighbors 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>
</div>
<div class="hb-copy-row">
<button class="hb-copy" type="button"><svg class="hb-ic hb-i-copy" viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg><svg class="hb-ic hb-i-done" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg><span class="hb-copy-label" aria-live="polite">Copy prompt</span></button>
<p class="hb-hint">Replace the words in brackets with your own element. Your settings are added at the end.</p>
</div>
</div>
<div class="hb-star-row"><p>Free and open source. If this helped, a star on GitHub helps other people find it.</p><a class="hb-star-btn" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg>Star on GitHub</a></div>
</section>
<section class="hb-about" aria-labelledby="hb-what-title">
<div class="hb-what">
<h2 id="hb-what-title">What it is</h2>
<div class="hb-what-text"><p>The full explanation is in <a href="README.md">README.md</a>.</p></div>
</div>
<div class="hb-fit">
<h2>Good for</h2>
<ul class="hb-tags hb-good"><li>Flags and banners</li><li>Playful pages</li><li>Fashion and textiles</li></ul>
<h3>Avoid on</h3>
<ul class="hb-tags hb-avoid"><li>Behind text</li><li>Serious content</li></ul>
</div>
</section>
<section class="hb-related" aria-labelledby="hb-related-title" hidden>
<h2 id="hb-related-title">Similar animations</h2>
<div class="hb-rel-list"></div>
</section>
</main>
<footer class="hb-foot"><span>Animation Handbook</span><a href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener">Source on GitHub</a><a href="#top">Back to top ↑</a></footer>
<script>
const cvs=document.getElementById('cvs'),ctx=cvs.getContext('2d');
const stage=document.getElementById('stage');
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=[];
let dragIdx=-1,dragMouse={x:0,y:0};
// See inside and Compare: the mode on show, and Compare's two cloths (null outside Compare) with their own wind clock and age
let mode='normal',halves=null,cT=0,cAge=0;
// Phones are screens up to 600px wide, or up to 500px tall when held sideways. They start at Low detail (16 × 12 points),
// a coarser grid that means far fewer constraint solves per frame; the visitor can still pick more. Low is the Detail choice
// marked data-hb-phone, which the home page's Copy prompt reads on phones too.
const PHONE=matchMedia('(max-width:600px),(max-height:500px)');
if(PHONE.matches){COLS=+document.querySelector('#detail-seg [data-hb-phone]').dataset.cols;ROWS=Math.round(COLS*.75);}
// The pressed Detail choice follows the start (this runs before the shared script reads the settings for "Your settings")
document.querySelectorAll('#detail-seg button').forEach(b=>{
const on=+b.dataset.cols===COLS;
b.classList.toggle('on',on);b.setAttribute('aria-pressed',String(on));
});
// 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);
}
// Hangs a fresh cloth and draws it, so a cloth that is paused (or not yet moving) is never an empty stage. With settle, 120 silent
// physics steps run first, so a cloth shown still (at load, or while paused) already hangs. In Compare both halves hang again too.
function initCloth(settle){
hang();
if(settle)for(let i=0;i<120;i++){windT+=16;update();}
if(halves)hangHalves(settle);else draw();
}
// A fresh flat grid, 80% as wide and 65% as tall as the world it hangs in (W by H), pinned as Hangs from says, with its links
function hang(){
const w=W*.8,h=H*.65;
const ox=W*.1,oy=H*.1;
const sw=w/COLS,sh=h/ROWS;
pts=[];prev=[];pinned=[];constraints=[];
dragIdx=-1; // a hold on a point of the old cloth ends with it
for(let r=0;r<=ROWS;r++){
for(let c=0;c<=COLS;c++){
pts.push([ox+c*sw,oy+r*sh]);
prev.push([ox+c*sw,oy+r*sh]);
pinned.push(false);
}
}
// Apply pins
const n=(r,c)=>r*(COLS+1)+c;
if(PIN_MODE==='top-corners'){pinned[n(0,0)]=true;pinned[n(0,COLS)]=true;}
else if(PIN_MODE==='top-edge'){for(let c=0;c<=COLS;c++)pinned[n(0,c)]=true;}
else if(PIN_MODE==='single'){pinned[n(0,0)]=true;}
// Structural constraints (horizontal + vertical)
for(let r=0;r<=ROWS;r++){for(let c=0;c<=COLS;c++){
if(c<COLS){const rest=Math.hypot(pts[n(r,c+1)][0]-pts[n(r,c)][0],pts[n(r,c+1)][1]-pts[n(r,c)][1]);constraints.push([n(r,c),n(r,c+1),rest]);}
if(r<ROWS){const rest=Math.hypot(pts[n(r+1,c)][0]-pts[n(r,c)][0],pts[n(r+1,c)][1]-pts[n(r,c)][1]);constraints.push([n(r,c),n(r+1,c),rest]);}
}}
}
function update(){
const windX=WIND*(Math.sin(windT*.0005)+.3)*.8;
// Verlet integrate
for(let i=0;i<pts.length;i++){
if(pinned[i])continue;
const vx=pts[i][0]-prev[i][0],vy=pts[i][1]-prev[i][1];
prev[i]=[...pts[i]];
pts[i][0]+=vx+windX*.04;
pts[i][1]+=vy+GRAVITY*.08;
// Bounds
if(pts[i][0]<0){pts[i][0]=0;prev[i][0]=pts[i][0]+vx*.5;}
if(pts[i][0]>W){pts[i][0]=W;prev[i][0]=pts[i][0]+vx*.5;}
if(pts[i][1]>H){pts[i][1]=H;prev[i][1]=pts[i][1]+vy*.5;}
}
// Drag
if(dragIdx>=0&&!pinned[dragIdx]){pts[dragIdx]=[dragMouse.x,dragMouse.y];prev[dragIdx]=[dragMouse.x,dragMouse.y];}
// Solve constraints (the dragged vertex is held at the pointer like a pin)
for(let it=0;it<ITERS;it++){
for(const[a,b,rest]of constraints){
const dx=pts[b][0]-pts[a][0],dy=pts[b][1]-pts[a][1];
const dist=Math.sqrt(dx*dx+dy*dy)||.001;
const diff=(dist-rest)/dist*.5;
if(!pinned[a]&&a!==dragIdx){pts[a][0]+=dx*diff;pts[a][1]+=dy*diff;}
if(!pinned[b]&&b!==dragIdx){pts[b][0]-=dx*diff;pts[b][1]-=dy*diff;}
}
}
}
function draw(){
if(halves)return drawHalves();
ctx.clearRect(0,0,W,H);drawCloth();
if(mode==='inside')drawInside();
}
// The cloth: its triangles, its mesh and, with Shows the points, every point (pinned ones red). cut (Compare's No links) leaves out
// every triangle and line that touches a pinned point: drawn, they would stretch from the pin down to the fallen sheet.
function drawCloth(cut){
const n=(r,c)=>r*(COLS+1)+c,off=cut?(i,j,k=j)=>pinned[i]||pinned[j]||pinned[k]:()=>false;
// Fill cloth triangles
for(let r=0;r<ROWS;r++){
for(let c=0;c<COLS;c++){
const a=pts[n(r,c)],b=pts[n(r,c+1)],cc=pts[n(r+1,c)],d=pts[n(r+1,c+1)];
const hue=(c/COLS*40+r/ROWS*20);
ctx.fillStyle=`hsla(${200+hue},60%,${30+r/ROWS*20}%,0.85)`;
if(!off(n(r,c),n(r,c+1),n(r+1,c))){ctx.beginPath();ctx.moveTo(a[0],a[1]);ctx.lineTo(b[0],b[1]);ctx.lineTo(cc[0],cc[1]);ctx.closePath();ctx.fill();}
if(!off(n(r,c+1),n(r+1,c+1),n(r+1,c))){ctx.beginPath();ctx.moveTo(b[0],b[1]);ctx.lineTo(d[0],d[1]);ctx.lineTo(cc[0],cc[1]);ctx.closePath();ctx.fill();}
}
}
// Mesh edges — one path, one stroke call per frame
ctx.strokeStyle='rgba(88,166,255,.12)';ctx.lineWidth=.5;ctx.beginPath();
for(let r=0;r<=ROWS;r++)for(let c=0;c<COLS;c++)if(!off(n(r,c),n(r,c+1))){ctx.moveTo(pts[n(r,c)][0],pts[n(r,c)][1]);ctx.lineTo(pts[n(r,c+1)][0],pts[n(r,c+1)][1]);}
for(let r=0;r<ROWS;r++)for(let c=0;c<=COLS;c++)if(!off(n(r,c),n(r+1,c))){ctx.moveTo(pts[n(r,c)][0],pts[n(r,c)][1]);ctx.lineTo(pts[n(r+1,c)][0],pts[n(r+1,c)][1]);}
ctx.stroke();
// Vertices
if(SHOW_VERTS){
pts.forEach((p,i)=>{
ctx.fillStyle=pinned[i]?'#f85149':'rgba(88,166,255,.7)';
ctx.beginPath();ctx.arc(p[0],p[1],pinned[i]?4:2,0,Math.PI*2);ctx.fill();
});
}
}
// 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 time
const dt=ts-lastT;if(dt<16)return;
lastT=ts;
behind+=Math.min(dt,50);
let steps=0;
while(behind>=FRAME-1&&steps<3){step();behind-=FRAME;steps++;}
if(steps)draw();
}
// One fixed step of Normal's cloth (See inside's too) or, in Compare, of both halves with the same wind. Without links every point
// gets the same push and No links ends flat on the floor or a wall, so both halves hang again every 300 steps (5 s), not while held.
function step(){
if(!halves){windT+=FRAME;update();return;}
if(halves[1].drag<0&&++cAge>300)hangHalves(false);
cT+=FRAME;halves.forEach(o=>inWorld(o,update));
}
// 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=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.
document.addEventListener('hb:pause',e=>{
paused=e.detail.paused;
if(paused){cancelAnimationFrame(raf);raf=null;}
else resume();
notes();
});
// The mode switch draws the mode at once. See inside draws over Normal's own cloth, which goes on as it is; Compare hangs two cloths
// of its own and leaves Normal's (points, held point, wind clock) untouched until it comes back (hung again after Hangs from, Detail
// or a size change).
const NAMES={normal:cvs.getAttribute('aria-label'),
inside:'The cloth as points joined by links: each link gold where it is stretched and pulls its points back, the pinned points red, with arrows for the push of the wind and of gravity',
compare:'Two cloths side by side: on the left, points with no links fall away from their pins; on the right, the linked cloth hangs and sways'};
document.addEventListener('hb:mode',e=>{
mode=e.detail.mode;
cvs.setAttribute('aria-label',NAMES[mode]);
if(mode!=='compare')halves=null;
else if(!halves){hangHalves(true);return;}
draw();
});
// Normal's own hang(), update(), drawing and grabbing run on one of Compare's cloths by taking Normal's place for a moment (points,
// last points, pins, links, held point, pointer, size, wind clock and columns); Normal's are then put back exactly.
function inWorld(o,fn){
const was=[pts,prev,pinned,constraints,dragIdx,dragMouse,W,H,windT,COLS];
[pts,prev,pinned,constraints,dragIdx,dragMouse,W,H,windT,COLS]=[o.pts,o.prev,o.pinned,o.links,o.drag,o.mouse,o.w,o.h,cT,o.cols];
fn();
[o.pts,o.prev,o.pinned,o.links,o.drag,o.mouse]=[pts,prev,pinned,constraints,dragIdx,dragMouse];
[pts,prev,pinned,constraints,dragIdx,dragMouse,W,H,windT,COLS]=was;
}
// Compare's two cloths, each a world of its own: its half (W/2 wide, from just low enough that its pins clear the half's name), the
// same Detail and pins, one wind clock; No links is the same grid with no links at all. As on arrival, they first take the page's
// 120 settling steps from a wind clock at zero (the same still each time); Reset, Hangs from or Detail while playing hangs them flat.
const names=stage.querySelectorAll('.half');
function hangHalves(settle){
const lb=names[0].offsetTop+names[0].offsetHeight,top=Math.max(0,(lb+9-H*.1)/.9);
if(settle)cT=0;
cAge=settle?120:0;
// On phones each half gets half the work: half the columns, so its points are as far apart as Normal's and both halves together cost what Normal does
const cols=PHONE.matches?Math.round(COLS/2):COLS;
halves=[0,1].map(i=>{const o={w:W/2,h:H-top,top,cols,drag:-1,mouse:{x:0,y:0}};inWorld(o,hang);if(!i)o.links=[];return o;});
if(settle)for(let i=0;i<120;i++){cT+=16;halves.forEach(o=>inWorld(o,update));}
draw();
}
// Compare: one canvas split down the middle, each half clipped, a thin line between; both mark their pinned points red
function drawHalves(){
const hw=W/2;ctx.clearRect(0,0,W,H);
halves.forEach((o,i)=>{ctx.save();ctx.beginPath();ctx.rect(i*hw,0,hw,H);ctx.clip();ctx.translate(i*hw,o.top);inWorld(o,()=>{drawCloth(!i);pinDots(4);});ctx.restore();});
ctx.fillStyle='#3a3c46';ctx.fillRect(hw-1,0,2,H);
}
function pinDots(r){ctx.fillStyle='#f85149';pts.forEach((p,i)=>{if(pinned[i]){ctx.beginPath();ctx.arc(p[0],p[1],r,0,Math.PI*2);ctx.fill();}});}
// See inside, over the real cloth dimmed to about a third: every link bold, colored by how far it is stretched past its length now
// (pale at its length, then three golds; one path and one stroke each), free points with Shows the points, pins red and ringed.
const BANDS=['rgba(232,235,242,.6)','#ecd28f','#f4b942','#ff8f2e'];
function drawInside(){
ctx.save();ctx.fillStyle='rgba(11,11,13,.66)';ctx.fillRect(0,0,W,H);
const paths=BANDS.map(()=>new Path2D());
for(const[a,b,rest]of constraints){
const s=Math.hypot(pts[b][0]-pts[a][0],pts[b][1]-pts[a][1])/rest-1,p=paths[s<.003?0:s<.01?1:s<.03?2:3];
p.moveTo(pts[a][0],pts[a][1]);p.lineTo(pts[b][0],pts[b][1]);
}
ctx.lineWidth=COLS>=40?1:1.5;ctx.lineCap='round';
paths.forEach((p,i)=>{ctx.strokeStyle=BANDS[i];ctx.stroke(p);});
if(SHOW_VERTS){ctx.fillStyle='rgba(88,166,255,.7)';pts.forEach((p,i)=>{if(!pinned[i]){ctx.beginPath();ctx.arc(p[0],p[1],2,0,Math.PI*2);ctx.fill();}});}
ctx.strokeStyle='#f85149';ctx.lineWidth=1.5;
pts.forEach((p,i)=>{if(pinned[i]){ctx.beginPath();ctx.arc(p[0],p[1],8,0,Math.PI*2);ctx.stroke();}});
pinDots(5);ctx.restore();drawPushes();
}
// The key's two pushes on one scale, the push a point gets each step: from the wind of this step (it grows, shrinks and turns back)
// and from gravity. The scale fits the strongest Wind both ways in the key's own canvas.
const key=stage.querySelector('.key'),pushCvs=key.querySelector('canvas'),pctx=pushCvs.getContext('2d'),windCap=key.querySelector('.wind');
const WMAX=Math.max(...[...document.querySelectorAll('#wind-seg button')].map(b=>+b.dataset.wind))*.8*.04;
function drawPushes(){
const w=pushCvs.clientWidth,h=pushCvs.clientHeight,dpr=Math.min(window.devicePixelRatio||1,2),cw=Math.round(w*dpr),ch=Math.round(h*dpr);
if(!w)return;
if(pushCvs.width!==cw||pushCvs.height!==ch){pushCvs.width=cw;pushCvs.height=ch;}
pctx.setTransform(dpr,0,0,dpr,0,0);pctx.clearRect(0,0,w,h);pctx.fillStyle=pctx.strokeStyle='#f4f4f2';pctx.lineWidth=2.5;
const x=w*.34,y=windCap.offsetHeight+6,S=Math.min((x-6)/(WMAX*.7),(w-x-6)/(WMAX*1.3));
arrow(x,y,x+WIND*(Math.sin(windT*.0005)+.3)*.8*.04*S,y);arrow(x,y,x,y+GRAVITY*.08*S);
pctx.beginPath();pctx.arc(x,y,4,0,Math.PI*2);pctx.fill();
}
function arrow(x0,y0,x1,y1){
const len=Math.hypot(x1-x0,y1-y0),ux=(x1-x0)/len,uy=(y1-y0)/len,hd=Math.min(9,len*.7),hw=hd*.6;if(len<1)return;
pctx.beginPath();pctx.moveTo(x0,y0);pctx.lineTo(x1-ux*hd,y1-uy*hd);pctx.stroke();
pctx.beginPath();pctx.moveTo(x1,y1);pctx.lineTo(x1-ux*hd-uy*hw,y1-uy*hd+ux*hw);pctx.lineTo(x1-ux*hd+uy*hw,y1-uy*hd-ux*hw);pctx.closePath();pctx.fill();
}
// The notes as the markup writes them, Compare's while nothing is pinned, and the still ones under reduced motion while paused
const noteIn=document.querySelector('[data-hb-for="inside"]'),noteCmp=document.querySelector('[data-hb-for="compare"]');
const NOTES={inside:noteIn.textContent,compare:noteCmp.textContent,
stillIn:'Inside, shown still: the cloth is points joined by links; gold links are stretched and pull their points back, red points are pinned, and the arrows show the wind and gravity.',
stillCmp:'Shown still: No links has slid away from its pins, since nothing holds the points to them; With links hangs from them as a cloth.',
none:'Hangs from is set to Nothing, so No links and With links both fall. Pick a pin in Try it to see the links hold the cloth up.'};
function notes(){
const still=paused&&matchMedia('(prefers-reduced-motion: reduce)').matches,put=(el,t)=>{if(el.textContent!==t)el.textContent=t;};
put(noteIn,still?NOTES.stillIn:NOTES.inside);
put(noteCmp,PIN_MODE==='none'?NOTES.none:still?NOTES.stillCmp:NOTES.compare);
key.classList.toggle('nopin',PIN_MODE==='none');
key.classList.toggle('top',PIN_MODE==='none'&&!paused);key.classList.toggle('still',PIN_MODE==='none'&&paused); // nothing pinned: the cloth falls to the floor while playing (key on top); shown still it hangs mid-air, clear of the bottom
}
matchMedia('(prefers-reduced-motion: reduce)').addEventListener('change',notes);
notes();
rebuild(true);resume();
// Drag interaction: Pointer Events cover mouse, touch and pen; capture keeps the drag alive outside the stage.
function getClosestVertex(x,y,maxDist=30){
let best=-1,bd=Infinity;
pts.forEach((p,i)=>{const d=Math.hypot(p[0]-x,p[1]-y);if(d<bd&&d<maxDist){bd=d;best=i;}});
return best;
}
// In Compare the pointer is read over the second half only, in that half's own place (a press on the first half grabs nothing)
const localPos=e=>{const r=cvs.getBoundingClientRect(),o=halves&&halves[1];return{x:e.clientX-r.left-(o?W/2:0),y:e.clientY-r.top-(o?o.top:0)};};
const held=fn=>halves?inWorld(halves[1],fn):fn();
// Only the main button or a finger grabs the cloth; a right click would otherwise leave the hold on after its menu opens.
stage.addEventListener('pointerdown',e=>{
if(!e.isPrimary||e.button!==0)return;
const p=localPos(e);
held(()=>{dragMouse=p;dragIdx=halves&&p.x<0?-1:getClosestVertex(dragMouse.x,dragMouse.y);});
try{stage.setPointerCapture(e.pointerId);}catch(_){}
});
// The position is only recorded; the cloth follows it on the next frame that moves on, so a paused cloth stays still.
stage.addEventListener('pointermove',e=>{if(!e.isPrimary)return;const p=localPos(e);held(()=>{if(dragIdx>=0)dragMouse=p;});});
const endDrag=e=>{if(!e.isPrimary)return;dragIdx=-1;if(halves)halves[1].drag=-1;};
['pointerup','pointercancel','lostpointercapture'].forEach(type=>stage.addEventListener(type,endDrag));
// A phone's address bar showing or hiding changes only the window's height, not the stage's, so nothing is hung again
window.addEventListener('resize',()=>{if(stage.clientWidth===W&&stage.clientHeight===H)return;rebuild(paused);});
function choices(id,pick){
const buttons=document.querySelectorAll('#'+id+' button');
buttons.forEach(b=>b.addEventListener('click',()=>{
buttons.forEach(x=>{x.classList.toggle('on',x===b);x.setAttribute('aria-pressed',String(x===b))});
pick(b.dataset);
}));
}
// Choosing what is already chosen must not hang a fresh cloth again
choices('pin-seg',d=>{if(d.pin===PIN_MODE)return;PIN_MODE=d.pin;notes();initCloth(paused);});
// Paused, Normal keeps its still; See inside draws its arrows again, and Compare hangs its halves again under the new setting
// See inside, paused: the cloth hangs again, settled under the new value, as stiffness (and wind and gravity) act only in the steps
const changed=()=>{if(paused&&halves)hangHalves(true);else if(paused&&mode==='inside')initCloth(true);};
choices('wind-seg',d=>{WIND=+d.wind;changed();});
choices('stiff-seg',d=>{ITERS=+d.iters;changed();});
choices('grav-seg',d=>{GRAVITY=+d.grav;changed();});
choices('detail-seg',d=>{
const n=+d.cols;
if(n===COLS)return;
COLS=n;ROWS=Math.round(COLS*.75);rebuild(paused);
});
document.getElementById('verts-tog').addEventListener('change',e=>{SHOW_VERTS=e.target.checked;if(paused)draw();});
// Reset hangs the cloth on show again: in Compare both halves, and Normal's cloth stays as it is
document.getElementById('btn-reset').addEventListener('click',()=>halves?hangHalves(paused):initCloth(paused));
</script>
</body>
</html>