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>Fluid / Liquid Simulation — Animation Handbook</title>
<meta name="description" content="Blobs drift and melt into each other like liquid. Best for hero backgrounds.">
<link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/fluid-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="Fluid / Liquid Simulation — Animation Handbook">
<meta property="og:description" content="Blobs drift and melt into each other like liquid. Best for hero backgrounds.">
<meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/fluid-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="Fluid / Liquid Simulation — Animation Handbook">
<meta name="twitter:description" content="Blobs drift and melt into each other like liquid. Best for hero backgrounds.">
<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": "Fluid / Liquid Simulation", "name": "Fluid / Liquid Simulation", "description": "Blobs drift and melt into each other like liquid. Best for hero backgrounds.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/fluid-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, Fluid / Liquid Simulation"}</script>
<style>
:root{--ui-accent:#3fd6c4}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
.stage{position:relative;background:#030810;touch-action:pan-y}
canvas{display:block;width:100%;height:100%}
.no-webgl{position:absolute;inset:0;display:none;align-items:center;justify-content:center;text-align:center;padding:24px;font-size:13px;line-height:1.7;color:rgba(255,255,255,.72)}
/* See inside and Compare: plain words over the picture (the picture itself is drawn by the shader) */
.key,.side{display:none}
.lbl{position:absolute;padding:3px 8px;border-radius:5px;background:rgba(3,8,16,.9);color:#f4f4f2;font:600 13px/1.2 var(--hb-font);white-space:nowrap}
.key{position:absolute;left:10px;top:10px;flex-direction:column;align-items:flex-start;gap:6px}
.key .lbl{position:static}
.stage[data-hb-mode="inside"] .key{display:flex}
.stage[data-hb-mode="compare"] .side{display:block}
.side{top:10px}
.side.first{left:10px}
.side.second{left:calc(50% + 10px)}
.stage.no-gl .key,.stage.no-gl .side{display:none!important}
</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="../canvas-particle-effect/" rel="prev" aria-label="Previous: Canvas Particle Effect"><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>Canvas Particle Effect</span></a><a href="../glassmorphism-animated/" rel="next" aria-label="Next: Glassmorphism Animated"><span><span class="hb-dir">Next: </span>Glassmorphism Animated</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.05 · 3D & Advanced</p>
<h1>Fluid / Liquid Simulation</h1>
<p class="hb-lede">Blobs drift and melt into each other like liquid. Best for hero backgrounds.</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, and one blob follows your pointer or finger. Pause it to look closely, or turn on slow motion.</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="Soft blobs drifting and melting into each other on a dark background"></canvas>
<div class="no-webgl" id="no-webgl">WebGL not available in this browser.</div>
<div class="key" aria-hidden="true"><span class="lbl k" data-hb-caption>White: each blob's circle</span><span class="lbl k" data-hb-caption>Gold: where two melt</span></div>
<p class="lbl side first" aria-hidden="true" data-hb-caption>Circles</p>
<p class="lbl side second" aria-hidden="true" data-hb-caption>Melting</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>
<label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="slow-tog" data-hb-slowmo autocomplete="off"><span>Slow motion</span></label>
</div>
<div class="hb-mode-notes" aria-live="polite">
<p data-hb-for="inside" hidden>Inside, each blob is a plain circle, outlined in white; where two come close, the melting adds liquid between them, shaded gold.</p>
<p data-hb-for="compare" hidden>On the left, Circles: the blobs only overlap, with sharp corners where they meet. On the right, Melting: they flow into one shape with soft necks between them.</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="melt-lbl">Melting</p>
<div class="seg" id="melt-seg" role="group" aria-labelledby="melt-lbl">
<button type="button" data-smooth="0.03" aria-pressed="false">A little</button>
<button type="button" data-smooth="0.08" class="on" aria-pressed="true">Medium</button>
<button type="button" data-smooth="0.15" aria-pressed="false">A lot</button>
</div>
<p class="hb-hint">How far apart two blobs start to melt together.</p>
</div>
<div class="hb-setting">
<p class="hb-setting-name" id="count-lbl">Number of blobs</p>
<div class="seg" id="count-seg" role="group" aria-labelledby="count-lbl">
<button type="button" data-balls="3" aria-pressed="false">Few</button>
<button type="button" data-balls="5" class="on" aria-pressed="true">Medium</button>
<button type="button" data-balls="8" aria-pressed="false">Many</button>
</div>
<p class="hb-hint">More blobs meet and merge more often.</p>
</div>
<div class="hb-setting">
<p class="hb-setting-name" id="speed-lbl">Speed</p>
<div class="seg" id="speed-seg" role="group" aria-labelledby="speed-lbl">
<button type="button" data-spd="0.5" aria-pressed="false">Slow</button>
<button type="button" data-spd="0.8" class="on" aria-pressed="true">Normal</button>
<button type="button" data-spd="1.3" aria-pressed="false">Fast</button>
</div>
<p class="hb-hint">Slow feels calm, like a lava lamp.</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="size-lbl">Blob size</p>
<div class="seg" id="size-seg" role="group" aria-labelledby="size-lbl">
<button type="button" data-rad="0.09" aria-pressed="false">Small</button>
<button type="button" data-rad="0.14" class="on" aria-pressed="true">Medium</button>
<button type="button" data-rad="0.2" aria-pressed="false">Large</button>
</div>
<p class="hb-hint">Bigger blobs touch and merge more.</p>
</div>
<div class="hb-setting">
<p class="hb-setting-name" id="color-lbl">Color</p>
<div class="swatches" id="color-sw" role="group" aria-labelledby="color-lbl">
<button type="button" aria-pressed="false" aria-label="Pink" data-color="#ff6f8b" style="background:#ff6f8b"></button>
<button type="button" aria-pressed="false" aria-label="White" data-color="#f4f4f2" style="background:#f4f4f2"></button>
<button type="button" class="on" aria-pressed="true" aria-label="Blue" data-color="#58a6ff" style="background:#58a6ff"></button>
<button type="button" aria-pressed="false" aria-label="Purple" data-color="#d2a8ff" style="background:#d2a8ff"></button>
<button type="button" aria-pressed="false" aria-label="Green" data-color="#56d364" style="background:#56d364"></button>
<button type="button" aria-pressed="false" aria-label="Orange" data-color="#ffa657" style="background:#ffa657"></button>
</div>
<p class="hb-hint">The color of the liquid.</p>
</div>
<div class="hb-setting">
<label class="hb-switch-row"><span>Glow</span><input class="hb-switch" type="checkbox" role="switch" id="glow-tog" checked autocomplete="off"></label>
<p class="hb-hint">A soft halo around the liquid.</p>
</div>
<div class="hb-setting">
<label class="hb-switch-row"><span>One blob follows the pointer</span><input class="hb-switch" type="checkbox" role="switch" id="mouse-tog" checked autocomplete="off"></label>
<p class="hb-hint">Moves one blob to your pointer or finger.</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 liquid blobs to [the section you want them in]. In a WebGL fragment shader, work out for every pixel its distance to each of a few moving circles, and blend those distances with a smooth minimum so circles that come close melt into one shape with soft necks between them, like drops of mercury. Move the circles on looping paths so they keep merging and separating; one can follow the pointer or a finger. Every pixel is checked against every circle, so draw fewer pixels on phones. If the visitor has reduced motion turned on, show the blobs 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>Hero backgrounds</li><li>Wellness brands</li><li>Creative studios</li><li>Splash screens</li></ul>
<h3>Avoid on</h3>
<ul class="hb-tags hb-avoid"><li>Behind text</li><li>Small elements</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 stage=document.getElementById('stage');
const cvs=document.getElementById('cvs');
const noWgl=document.getElementById('no-webgl');
const slowTog=document.getElementById('slow-tog');
let W,H,gl,prog,U={},raf=null,paused=false,lastT=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];
// See inside and Compare: the mode on show, and what the canvas says it shows in each one
let mode='normal';
const LABELS={normal:cvs.getAttribute('aria-label'),
inside:'The blobs dimmed, each one\'s own circle outlined in white and the places where two melt together shaded gold',
compare:'Two copies of the blobs side by side: hard circles that only overlap on the left, blobs that melt together on the right'};
const BG=[3/255,8/255,16/255];
// The pointer is recorded at once, but the picture takes it only when a frame moves on,
// so a repaint while paused shows a new setting and moves nothing.
let mouseX=.5,mouseY=.5,shownX=.5,shownY=.5;
const VS=`attribute vec2 aPos;void main(){gl_Position=vec4(aPos,0.,1.);}`;
const FS=`
precision mediump float;
uniform vec2 uRes,uOrigin;uniform float uT;uniform int uBalls,uView;
uniform float uSmooth,uRad;uniform vec2 uMouse;uniform bool uGlow,uMouseBall;
uniform vec3 uColor,uBG;
float smin(float a,float b,float k){
float h=clamp(.5+.5*(b-a)/k,0.,1.);
return mix(b,a,h)-k*h*(1.-h);
}
vec2 ball(int i,float t){
float fi=float(i);
float s=1.3+fi*.4,o=fi*2.1;
return vec2(.5+.38*sin(t*s+o),.5+.38*cos(t*s*.7+o*1.3));
}
void main(){
// uOrigin is where this picture starts on the canvas: Compare draws two pictures side by side
vec2 uv=(gl_FragCoord.xy-uOrigin)/uRes;
uv.y=1.-uv.y;
float d=10.,hard=10.,edge=10.;
for(int i=0;i<8;i++){
if(i>=uBalls)break;
vec2 c=(i==0&&uMouseBall)?uMouse:ball(i,uT);
float bd=length((uv-c)*vec2(uRes.x/uRes.y,1.))-uRad;
d=smin(d,bd,uSmooth);
hard=min(hard,bd);
edge=min(edge,abs(bd));
}
// Compare's first picture: the plain circles, with no melting between them
if(uView==2)d=hard;
float inside=smoothstep(.01,-.01,d);
vec3 rim=uColor*pow(clamp(1.-abs(d)/.05,0.,1.),3.);
float glow=uGlow?exp(-max(d,0.)/.08)*.4:0.;
vec3 col=mix(uBG,uColor,inside)+rim*.5+uColor*glow;
// See inside: the liquid dimmed; where the melting adds liquid outside every plain circle, gold; each plain circle outlined
if(uView==1){
col*=.45;
float melt=(1.-smoothstep(-.004,.004,d))*smoothstep(0.,.004,hard);
col=mix(col,vec3(1.,.82,.36),melt*.95);
col=mix(col,vec3(1.),1.-smoothstep(.002,.007,edge));
}
gl_FragColor=vec4(col,1.);
}`;
// A failed shader is otherwise a silent black canvas — say so instead.
function fail(msg){stage.classList.add('no-gl');gl=null;cvs.style.display='none';
noWgl.textContent=msg;noWgl.style.display='flex';}
function init(){
gl=cvs.getContext('webgl');
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,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 uOrigin uT uBalls uView 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);
const aPos=gl.getAttribLocation(prog,'aPos');
gl.enableVertexAttribArray(aPos);
gl.vertexAttribPointer(aPos,2,gl.FLOAT,false,0,0);
return true;
}
function resize(){
// Full DPR on desktop, capped lower on phones (600px wide or less, or 500px tall or less when held sideways) — 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||window.innerHeight<=500?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.
redraw();
}
// The loop keeps exactly one pending frame in raf. Slow motion adds a third of the frame's time to the clock.
function render(ts){
raf=paused?null:requestAnimationFrame(render);
const dt=ts-lastT;if(dt<16)return;
// Accumulate sim time so speed changes and pauses never make the blobs jump.
if(!paused){simT+=Math.min(dt,100)/1000*SPD/(slowTog.checked?3:1);shownX=mouseX;shownY=mouseY;}
lastT=ts;
gl.useProgram(prog);
gl.uniform1f(U.uT,simT);
gl.uniform1i(U.uBalls,BALLS);
gl.uniform1f(U.uSmooth,SMOOTH);
gl.uniform1f(U.uRad,RAD);
gl.uniform2f(U.uMouse,shownX,shownY);
gl.uniform1i(U.uGlow,GLOW?1:0);
gl.uniform3fv(U.uColor,COLOR);
gl.uniform3fv(U.uBG,BG);
// Compare: one context, two pictures side by side with a thin line between them, the plain circles on the left and the melting
// blobs on the right; the pointer, read over the right half only, moves the same blob in both, so the blobs match.
if(mode==='compare'){
const half=Math.floor(W/2),gap=Math.max(1,Math.round(W/400));
gl.viewport(0,0,W,H);gl.clearColor(.17,.17,.2,1);gl.clear(gl.COLOR_BUFFER_BIT);
view(0,half-gap,2,MOUSE_BALL);
view(half+gap,W-half-gap,0,MOUSE_BALL);
}else view(0,W,mode==='inside'?1:0,MOUSE_BALL);
}
// One picture of the blobs in a part of the canvas, x and w in canvas pixels: kind 0 as it is, 1 See inside, 2 hard circles
function view(x,w,kind,mouseBall){
gl.viewport(x,0,w,H);
gl.uniform2f(U.uOrigin,x,0);
gl.uniform2f(U.uRes,w,H);
gl.uniform1i(U.uView,kind);
gl.uniform1i(U.uMouseBall,mouseBall?1:0);
gl.drawArrays(gl.TRIANGLE_STRIP,0,4);
}
function start(){if(raf||!gl)return;lastT=performance.now();raf=requestAnimationFrame(render);}
// While paused a setting or a resize draws the picture again, so the change shows without anything moving.
// It hands render a time 17 ms on, not 16: adding 16 to a large time can round to just under 16 and the frame gate would skip the repaint.
function redraw(){if(gl&&paused)render(lastT+17);}
// Registered at the top level, before the shared script (deferred) can run: under reduced motion it pauses the
// loop on arrival, which this listener must catch. Pause cancels the pending frame and the picture stays;
// Play calls start(), which carries on from the current clock.
document.addEventListener('hb:pause',e=>{
paused=e.detail.paused;
if(paused){cancelAnimationFrame(raf);raf=null;}
else start();
});
// The mode switch: the next frame draws the mode, and while paused one frame is drawn at once. The canvas's name says what it shows.
document.addEventListener('hb:mode',e=>{
mode=e.detail.mode;
cvs.setAttribute('aria-label',LABELS[mode]);
redraw();
});
function hexToRgb(hex){return[parseInt(hex.slice(1,3),16)/255,parseInt(hex.slice(3,5),16)/255,parseInt(hex.slice(5,7),16)/255];}
// Shader uv.y is flipped to top-down, so the pointer y must be top-down too.
// A finger counts as the pointer: a tap moves the blob there and a sideways drag moves it along.
function aim(e){
const r=cvs.getBoundingClientRect();
// In Compare the pointer is read over the second picture only (a pointer over the first half moves nothing), and its blob
// moves in both pictures, so they match
if(mode==='compare'){const x=e.clientX-r.left-r.width/2;if(x<0)return;mouseX=x/(r.width/2);}
else mouseX=(e.clientX-r.left)/r.width;
mouseY=(e.clientY-r.top)/r.height;
}
if(init()){
resize();lastT=performance.now();
// The first picture: draws a frame at once and starts the loop.
render(lastT+17);
stage.addEventListener('pointermove',aim);
stage.addEventListener('pointerdown',aim);
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);
});
}
function choices(id,pick){
const buttons=document.querySelectorAll('#'+id+' button');
buttons.forEach(b=>b.addEventListener('click',()=>{
buttons.forEach(x=>{x.classList.toggle('on',x===b);x.setAttribute('aria-pressed',String(x===b))});
pick(b.dataset);
}));
}
choices('melt-seg',d=>{SMOOTH=+d.smooth});
choices('count-seg',d=>{BALLS=+d.balls});
choices('speed-seg',d=>{SPD=+d.spd});
choices('size-seg',d=>{RAD=+d.rad});
choices('color-sw',d=>{COLOR=hexToRgb(d.color)});
document.getElementById('glow-tog').addEventListener('change',e=>{GLOW=e.target.checked});
document.getElementById('mouse-tog').addEventListener('change',e=>{MOUSE_BALL=e.target.checked});
// While paused, any click or change in Try it still repaints one frame so the result is visible.
['click','change'].forEach(type=>document.querySelector('.hb-try').addEventListener(type,redraw));
</script>
</body>
</html>