176 web animation techniques, each a live demo with plain settings and a ready-made prompt for your AI assistant. No dependencies, no build step.
HTML ai-promptsanimationcss-animationsfrontendgithub-pagesjavascriptmicrointeractionsmotion-designno-dependenciesreferencescroll-animationui-animationweb-animationweb-developmentwebgl
feat: Volumetric Smoke / 3D Noise shows the smoke beside a side view of the cloud with a dot at each step along seven lines of sight (See inside) and a flat picture beside the 3D cloud (Compare)
matind82b9757fc63
diff --git a/animations/06-3d-advanced/volumetric-smoke/index.html b/animations/06-3d-advanced/volumetric-smoke/index.htmlindex 1889228f..356ab960 100644--- a/animations/06-3d-advanced/volumetric-smoke/index.html+++ b/animations/06-3d-advanced/volumetric-smoke/index.html@@ -21,12 +21,27 @@<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": "Volumetric Smoke / 3D Noise", "name": "Volumetric Smoke / 3D Noise", "description": "Soft smoke curls upward, drawn as a real 3D cloud. Best for moody backgrounds.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/volumetric-smoke/", "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, Volumetric Smoke / 3D Noise"}</script><style>- :root{--ui-accent:#3fd6c4}+ :root{--ui-accent:#3fd6c4;--gold:#ffbf3c}*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}.stage{position:relative;background:#030810}canvas{display:block;width:100%;height:100%}.msg{position:absolute;inset:0;display:none;align-items:center;justify-content:center;text-align:center;padding:clamp(16px,4vw,32px);font-size:13px;line-height:1.7;color:rgba(255,255,255,.72);white-space:pre-wrap;overflow-y:auto}.msg.on{display:flex}+ /* See inside and Compare: lines and plain words over the picture (the picture itself is drawn by the shader) */+ .ov,.cap{display:none;position:absolute;pointer-events:none}+ .ov{inset:0;width:100%;height:100%}+ .cap{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}+ .cap.gold{color:var(--gold)}+ .stage[data-hb-mode="inside"] .ov,.stage[data-hb-mode="compare"] .ov,.stage[data-hb-mode="inside"] .c-in,.stage[data-hb-mode="compare"] .c-cmp{display:block}+ .stage .cap[hidden],.stage.no-gl .ov,.stage.no-gl .cap{display:none!important}+ .ov *{fill:none;stroke-linecap:round;stroke-width:2}+ .ov .div{stroke:#2b2b33}+ .ov .ray{stroke:rgba(244,244,242,.3);stroke-width:1}+ .ov .dots{stroke:rgba(244,244,242,.8);stroke-width:var(--dot)}+ .ov .arrow{stroke:#f4f4f2}+ .ov .eye{fill:#f4f4f2}+ .ov .gold{stroke:var(--gold)}+ .ov .ray.gold{stroke-width:1.5}</style><link rel="stylesheet" href="../../../assets/css/demo-page.css?v=10"><script src="../../../assets/js/demo-page.js?v=10" defer></script>@@ -49,14 +64,32 @@<span class="hb-num" aria-hidden="true">1</span><div><h2 id="hb-watch-title">Watch it</h2><p>It moves by itself. Pause it to look closely, or turn on slow motion to see each part of the movement.</p></div></div>+ <div class="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 smoke rising and curling against a dark background"></canvas><div class="msg" id="msg" role="status"></div>+ <svg class="ov" id="ov" aria-hidden="true"></svg>+ <span class="cap c-in" data-cap="front" data-hb-caption aria-hidden="true">What you see</span>+ <span class="cap c-in gold" data-cap="pixel" data-hb-caption aria-hidden="true">This pixel</span>+ <span class="cap c-in" data-cap="side" data-hb-caption aria-hidden="true">From the side</span>+ <span class="cap c-in" data-cap="eye" data-hb-caption aria-hidden="true">Your eye</span>+ <span class="cap c-in gold" data-cap="line" data-hb-caption aria-hidden="true">Its line of sight: a dot at each step</span>+ <span class="cap c-in" data-cap="light" data-hb-caption aria-hidden="true">Light</span>+ <span class="cap c-cmp" data-cap="flat" data-hb-caption aria-hidden="true">Flat picture</span>+ <span class="cap c-cmp" data-cap="cloud" data-hb-caption aria-hidden="true">3D cloud</span></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>From the side, each pixel's line of sight takes steps through the cloud (the dots), adding up the smoke it meets. Fine grain staggers the steps, so no stripes form.</p>+ <p data-hb-for="compare" hidden>Flat picture is the same smoke pattern drawn once, flat and unlit; 3D cloud adds up smoke along each line of sight and shades it from the light, so it looks soft and deep.</p>+ </div></section><section class="hb-step hb-try" aria-labelledby="hb-try-title">@@ -164,8 +197,8 @@ precision highp float;#elseprecision mediump float;#endif-uniform vec2 uRes;uniform float uT,uDens,uRise;uniform int uSteps;-uniform bool uWind,uDither;uniform vec3 uSmoke,uBG;+uniform vec2 uRes,uOrigin,uSc;uniform float uT,uDens,uRise;uniform int uSteps,uView;+uniform bool uWind,uDither;uniform vec3 uSmoke,uBG;uniform vec4 uSl;// 3D value noise via hashfloat h31(vec3 p){return fract(sin(dot(p,vec3(127.1,311.7,74.7)))*43758.5);}@@ -197,14 +230,43 @@ float dither(vec2 co){return fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5)-.5;}+// The three short taps toward the light: 1 in full light, .15 in full shade+float lit(vec3 p,float stepSz){+ vec3 lightDir=normalize(vec3(1.5,2.,1.));+ float shadow=1.;+ for(int s=1;s<=3;s++){+ vec3 lp=p+lightDir*float(s)*.18;+ shadow*=exp(-density(lp,uT)*stepSz*2.5);+ }+ return .15+.85*shadow;+}++// See inside, from the side: the cloud's middle slice (x = 0), each spot colored by the same density() and light as the smoke+vec3 slice(){+ vec2 f=(gl_FragCoord.xy-uOrigin)/uRes;+ vec3 p=vec3(0.,uSl.y+f.y*uSl.w,uSl.x-f.x*uSl.z);+ vec3 bg=uBG*2.2;+ float d=density(p,uT);+ if(d<=0.)return bg;+ return mix(bg,uSmoke*lit(p,3./float(uSteps)),1.-exp(-d*9.));+}++// Compare, the flat picture: density() read once where each pixel's line of sight meets the column's middle plane (z = 0), no steps, no light+vec3 flatPic(vec2 uv){+ float d=density(vec3(uv*(3./.9),0.),uT);+ return mix(uBG,uSmoke*.85,smoothstep(0.,.008,d)*.19);+}+void main(){- vec2 uv=(gl_FragCoord.xy-.5*uRes)/min(uRes.x,uRes.y);+ vec2 uv=(gl_FragCoord.xy-uOrigin-.5*uRes)/min(uRes.x,uRes.y);+ uv=uv*uSc.x+vec2(0.,uSc.y);+ if(uView==1){gl_FragColor=vec4(slice(),1.);return;}+ if(uView==2){gl_FragColor=vec4(flatPic(uv),1.);return;}vec3 ro=vec3(0.,0.,3.);vec3 rd=normalize(vec3(uv,-.9));vec3 col=vec3(0.);float transmit=1.,stepSz=3./float(uSteps);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++){if(i>=uSteps)break;@@ -212,13 +274,7 @@ void main(){if(p.y>2.5||p.y<-.3){t+=stepSz;continue;}float d=density(p,uT);if(d>0.){- // Shadow along light ray (3 steps)- float shadow=1.;- for(int s=1;s<=3;s++){- vec3 lp=p+lightDir*float(s)*.18;- shadow*=exp(-density(lp,uT)*stepSz*2.5);- }- vec3 smokeCol=uSmoke*(.15+.85*shadow);+ vec3 smokeCol=uSmoke*lit(p,stepSz);float alpha=1.-exp(-d*stepSz*8.);col+=transmit*alpha*smokeCol;transmit*=1.-alpha;@@ -232,7 +288,7 @@ void main(){const stage=document.getElementById('stage'),cvs=document.getElementById('cvs');const msgEl=document.getElementById('msg'),slowTog=document.getElementById('slow-tog');-const UNIFORMS=['uRes','uT','uDens','uRise','uSteps','uWind','uDither','uSmoke','uBG'];+const UNIFORMS=['uRes','uOrigin','uSc','uSl','uView','uT','uDens','uRise','uSteps','uWind','uDither','uSmoke','uBG'];// The clock and the rise start where the old still frame was (2 seconds in, at the default speed), so the first picture is that framelet W=0,H=0,gl=null,prog=null,U=null,raf=null,paused=false,last=null,curT=2,rise=1.2,wasPhone=false,lost=false;let DENS=0.7,SPD=0.6,STEPS=32,WIND=true,DITHER=true;@@ -243,7 +299,7 @@ const PHONE=matchMedia('(max-width:600px),(max-height:500px)');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];}// A canvas that can never draw is also taken out of the page for screen readers (hide); a lost context leaves it under the message.-function fail(msg,hide){msgEl.textContent=msg;msgEl.classList.add('on');if(hide)cvs.hidden=true;}+function fail(msg,hide){msgEl.textContent=msg;msgEl.classList.add('on');stage.classList.add('no-gl');if(hide)cvs.hidden=true;}function init(){gl=cvs.getContext('webgl');if(!gl){fail('WebGL is unavailable in this browser, so the volume cannot be ray marched.',true);return false;}@@ -293,14 +349,109 @@ function render(ts){}function draw(t){gl.useProgram(prog);- gl.uniform2f(U.uRes,W,H);gl.uniform1f(U.uT,t);+ gl.uniform1f(U.uT,t);gl.uniform1f(U.uDens,DENS);gl.uniform1f(U.uRise,rise);gl.uniform1i(U.uSteps,steps());gl.uniform1i(U.uWind,WIND?1:0);gl.uniform1i(U.uDither,DITHER?1:0);gl.uniform3fv(U.uSmoke,SMOKE);gl.uniform3fv(U.uBG,BG);+ if(!views){paint(0,0,W,H,0,1,0);return;}+ // One context, a viewport for each picture (given in stage pixels)+ gl.viewport(0,0,W,H);gl.clearColor(BG[0],BG[1],BG[2],1);gl.clear(gl.COLOR_BUFFER_BIT);+ const kx=W/stage.clientWidth,ky=H/stage.clientHeight;+ for(let i=0;i<views.length;i++){+ const v=views[i],h=Math.round(v.h*ky);+ paint(Math.round(v.x*kx),H-Math.round(v.y*ky)-h,Math.round(v.w*kx),h,v.kind,v.sc,v.cy,v.sl);+ }+}+// One picture in a part of the canvas: kind 0 the smoke, 1 the side slice, 2 the flat picture+function paint(x,y,w,h,kind,sc,cy,sl){+ gl.viewport(x,y,w,h);+ gl.uniform2f(U.uOrigin,x,y);gl.uniform2f(U.uRes,w,h);gl.uniform2f(U.uSc,sc,cy);+ gl.uniform1i(U.uView,kind);if(sl)gl.uniform4fv(U.uSl,sl);gl.drawArrays(gl.TRIANGLE_STRIP,0,4);}+// See inside and Compare: the mode on show, the pictures it draws (null in Normal) and what the canvas says it shows+const ov=document.getElementById('ov'),caps={};+document.querySelectorAll('[data-cap]').forEach(c=>{caps[c.dataset.cap]=c;});+const LABELS={normal:cvs.getAttribute('aria-label'),+ inside:'The smoke beside a side view of the cloud, with lines of sight from the eye taking steps through it and an arrow where the light comes from',+ compare:'Two pictures of the smoke side by side: a flat, unlit noise pattern on the left and the soft 3D cloud on the right'};+let mode='normal',views=null;+// The seven lines of sight leave rows of the front view (a share of its height above the middle); the fifth is the gold one.+// Fine grain starts each line's steps a fixed part of a step further in; with it off every line steps alike.+const ROWS=[-.25,-.125,0,.125,.25,.375,.5],GOLD=4,OFFS=[.35,-.3,.1,-.45,.4,-.15,.25];+const LINE_FULL='Its line of sight: a dot at each step',LINE_SHORT='A dot at each step';+let taken=[],marks=[];+// A caption goes at the first spot (a function of its size) that stays inside the stage and clear of the marks and other captions+function put(el,spots){+ el.hidden=false;+ const w=el.offsetWidth,h=el.offsetHeight,cw=stage.clientWidth,ch=stage.clientHeight;+ for(const [x,y] of spots(w,h)){+ if(x<2||y<2||x+w>cw-2||y+h>ch-2)continue;+ if(marks.some(m=>m[0]>x-6&&m[0]<x+w+6&&m[1]>y-6&&m[1]<y+h+6))continue;+ if(taken.some(b=>x<b[2]+4&&x+w>b[0]-4&&y<b[3]+4&&y+h>b[1]-4))continue;+ el.style.left=x+'px';el.style.top=y+'px';taken.push([x,y,x+w,y+h]);return true;+ }+ el.hidden=true;return false;+}+function rebuild(){+ views=null;ov.innerHTML='';taken=[];marks=[];+ for(const k in caps)caps[k].hidden=true;+ if(mode==='normal'||!live())return;+ const cw=stage.clientWidth,ch=stage.clientHeight,g=2,phone=PHONE.matches,svg=[];+ ov.setAttribute('viewBox',`0 0 ${cw} ${ch}`);+ if(mode==='compare'){+ // Each half's name has a band of its own, and its picture starts under it+ const half=Math.floor((cw-g)/2),band=32;+ views=[{x:0,y:band,w:half,h:ch-band,kind:2,sc:1,cy:0},{x:half+g,y:band,w:cw-half-g,h:ch-band,kind:0,sc:1,cy:0}];+ ov.innerHTML=`<path class="div" d="M${half+1} 0V${ch}M0 ${band-1}H${cw}"/>`;+ put(caps.flat,()=>[[8,5]]);put(caps.cloud,()=>[[half+g+8,5]]);+ return;+ }+ // The real smoke at the left (a strip across the top when the box is narrow), the side view beside (under) it+ const stack=cw<480,fw=stack?cw:Math.round(cw*.38),fh=stack?Math.round(ch*.34):ch,m=Math.min(fw,fh);+ const front={x:0,y:0,w:fw,h:fh,kind:0,sc:stack?.7:1,cy:stack?.15:0};+ const side={x:stack?0:fw+g,y:stack?fh+g:0,w:stack?cw:cw-fw-g,h:stack?ch-fh-g:ch,kind:1};+ // The side view keeps both directions in proportion: s pixels to a unit, the eye at z 3 and the column's middle at z 0+ const s=Math.min(side.w/4.05,side.h/3.5),zL=3.4+(side.w/s-4.05)/2,yT=2.7+(side.h/s-3.5)/2;+ side.sl=[zL,yT-side.h/s,side.w/s,side.h/s];+ views=[front,side];+ svg.push(`<path class="div" d="${stack?`M0 ${fh+1}H${cw}`:`M${fw+1} 0V${ch}`}"/>`);+ const X=z=>side.x+(zL-z)*s,Y=y=>side.y+(yT-y)*s,n=steps(),eye=[X(3),Y(0)];+ ROWS.forEach((r,i)=>{+ const uy=front.cy+front.sc*r*fh/m,len=Math.hypot(uy,.9),at=t=>[X(3-.9*t/len),Y(uy*t/len)],c=i===GOLD?' gold':'';+ svg.push(`<path class="ray${c}" d="M${at(0)}L${at(3.2)}"/>`);+ let d='';+ for(let j=0;j<n;j++){const p=at(.2+(j+(DITHER?OFFS[i]:0))*3/n);d+=`M${p[0].toFixed(1)} ${p[1].toFixed(1)}h0`;}+ svg.push(`<path class="dots${c}" d="${d}"/>`);+ for(let k=0;k<=30;k++)marks.push(at(3.2*k/30));+ });+ ov.style.setProperty('--dot',Math.max(3,Math.min(4,s/28)));+ svg.push(`<circle class="eye" cx="${eye[0]}" cy="${eye[1]}" r="5"/>`);marks.push(eye);+ // The light comes from above, on the eye's side: the arrow points the way it travels+ const A=[X(.3),Y(2.5)],B=[X(-.06),Y(1.78)],L=Math.hypot(B[0]-A[0],B[1]-A[1]),ux=(B[0]-A[0])/L,uy=(B[1]-A[1])/L;+ svg.push(`<path class="arrow" d="M${A}L${B}M${B[0]-ux*9-uy*5},${B[1]-uy*9+ux*5}L${B}L${B[0]-ux*9+uy*5},${B[1]-uy*9-ux*5}"/>`);+ for(let k=0;k<=8;k++)marks.push([A[0]+(B[0]-A[0])*k/8,A[1]+(B[1]-A[1])*k/8]);+ const px=fw/2,py=fh*.25;+ svg.push(`<g class="cross gold"><circle cx="${px}" cy="${py}" r="9"/><path d="M${px-15} ${py}h8M${px+7} ${py}h8M${px} ${py-15}v8M${px} ${py+7}v8"/></g>`);+ marks.push([px,py],[px-15,py],[px+15,py],[px,py-15],[px,py+15]);+ ov.innerHTML=svg.join('');+ put(caps.side,()=>[[side.x+8,side.y+8]]);+ put(caps.eye,w=>[12,18,24,30].map(dy=>[Math.max(6,eye[0]-w/2),eye[1]+dy]));+ put(caps.light,(w,h)=>[[A[0]+12,A[1]-h/2],[A[0]-w-12,A[1]-h/2]]);+ const under=(w,h)=>[[side.x+8,side.y+16+caps.side.offsetHeight],[side.x+side.w-w-8,side.y+8]];+ caps.line.textContent=phone?LINE_SHORT:LINE_FULL;+ if(!put(caps.line,under)&&!phone){caps.line.textContent=LINE_SHORT;put(caps.line,under);}+ if(!phone){+ put(caps.front,()=>[[8,8]]);+ if(put(caps.pixel,(w,h)=>[[fw-w-8,py-h/2]])){+ const x2=parseFloat(caps.pixel.style.left)-2;+ ov.insertAdjacentHTML('beforeend',`<path class="cross gold" d="M${px+11} ${py}H${x2}"/>`);+ }+ }+}+// Play carries on from the clock and the rise where they stopped; it never stacks a second loop.function start(){if(raf!==null||!live())return;last=null;raf=requestAnimationFrame(render);}function stop(){if(raf!==null)cancelAnimationFrame(raf);raf=null;}@@ -310,13 +461,32 @@ function stop(){if(raf!==null)cancelAnimationFrame(raf);raf=null;}document.addEventListener('hb:pause',e=>{paused=e.detail.paused;if(paused)stop();else start();+ words();+});+// Under reduced motion the notes say "Shown still" while the smoke is paused and the markup's own words while it plays+const noteEl={inside:document.querySelector('[data-hb-for="inside"]'),compare:document.querySelector('[data-hb-for="compare"]')};+const NOTE_MOVING={inside:noteEl.inside.textContent,compare:noteEl.compare.textContent};+const NOTE_STILL={inside:"Shown still from the side: each pixel's line of sight takes steps through the cloud (the dots), adding up the smoke it meets. Fine grain staggers the steps, so no stripes form.",+ compare:'Shown still: Flat picture is the same smoke pattern drawn once, flat and unlit; 3D cloud adds up smoke along each line of sight and shades it from the light.'};+function words(){+ const still=matchMedia('(prefers-reduced-motion: reduce)').matches&&paused;+ for(const k in noteEl){const w=(still?NOTE_STILL:NOTE_MOVING)[k];if(noteEl[k].textContent!==w)noteEl[k].textContent=w;}+}++// The mode switch: the pictures it draws are made and drawn at once, also while paused. The canvas's name says what it shows.+document.addEventListener('hb:mode',e=>{+ mode=e.detail.mode;+ cvs.setAttribute('aria-label',LABELS[mode]);+ rebuild();+ if(live())draw(curT);});if(init()){layout(true);draw(curT); // the first picture, so a loop that is paused on arrival never shows an empty stagestart();- window.addEventListener('resize',()=>{if(layout()&&live())draw(curT);});+ window.addEventListener('resize',()=>{const c=layout();rebuild();if((c||views)&&live())draw(curT);});+ document.fonts.ready.then(rebuild);cvs.addEventListener('webglcontextlost',e=>{e.preventDefault();lost=true;stop();fail('WebGL context lost — reload the page to restart the render.');});}@@ -329,10 +499,10 @@ function choices(id,pick){}choices('dens-seg',d=>{DENS=+d.dens;refresh();});choices('speed-seg',d=>{SPD=+d.spd;});-choices('steps-seg',d=>{STEPS=+d.steps;refresh();});+choices('steps-seg',d=>{STEPS=+d.steps;rebuild();refresh();});choices('smoke-sw',d=>{SMOKE=h2r(d.color);refresh();});document.getElementById('wind-tog').addEventListener('change',e=>{WIND=e.target.checked;refresh();});-document.getElementById('dither-tog').addEventListener('change',e=>{DITHER=e.target.checked;refresh();});+document.getElementById('dither-tog').addEventListener('change',e=>{DITHER=e.target.checked;rebuild();refresh();});</script></body></html>