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: add 13 techniques + category filter; fix missing READMEs, offline & docs
matin3dd41b580cb1
diff --git a/CLAUDE.md b/CLAUDE.mdindex 68cd480c..c2c98a0c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -44,10 +44,11 @@ Every animation README has exactly these sections:1. Scroll-Based — scroll-driven techniques (folder: 01-scroll-based)2. Entrance & Exit — element enter, exit, reveal animations (folder: 02-entrance-and-exit)-3. Micro-Interactions — hover, click, focus, loading, UI feedback (folder: 03-micro-interactions)-4. Text & Typography — text-specific animations (folder: 04-text-typography)-5. 3D & Advanced — WebGL, shaders, particles, 3D transforms (folder: 05-3d-advanced)-6. Ambient & Background — passive looping effects (folder: 06-ambient-background)+3. Page Transitions — full-page/route transitions (folder: 03-page-transitions)+4. Micro-Interactions — hover, click, focus, loading, UI feedback (folder: 04-micro-interactions)+5. Text & Typography — text-specific animations (folder: 05-text-typography)+6. 3D & Advanced — WebGL, shaders, particles, 3D transforms (folder: 06-3d-advanced)+7. Ambient & Background — passive looping effects (folder: 07-ambient-background)## Distinction: technique vs toolThis atlas catalogs **techniques**, not libraries. GSAP, Framer Motion,diff --git a/README.md b/README.mdindex b7edfe0f..4f8eea40 100644--- a/README.md+++ b/README.md@@ -2,7 +2,7 @@**[Live demo →](https://matinmonshizadeh.github.io/animation-handbook/)**-A visual reference of 100 web animation techniques. Each entry is a+A visual reference of 113 web animation techniques. Each entry is aself-contained HTML demo with an explanation of the mechanic — openany file in a browser and it runs offline, no build step.@@ -10,13 +10,13 @@ any file in a browser and it runs offline, no build step.| # | Category | Animations ||---|----------|-----------|-| 01 | [Scroll-Based](animations/01-scroll-based/) | 19 |+| 01 | [Scroll-Based](animations/01-scroll-based/) | 20 || 02 | [Entrance & Exit](animations/02-entrance-and-exit/) | 13 || 03 | [Page Transitions](animations/03-page-transitions/) | 12 |-| 04 | [Micro-Interactions](animations/04-micro-interactions/) | 17 |-| 05 | [Text & Typography](animations/05-text-typography/) | 11 |-| 06 | [3D & Advanced](animations/06-3d-advanced/) | 16 |-| 07 | [Ambient & Background](animations/07-ambient-background/) | 12 |+| 04 | [Micro-Interactions](animations/04-micro-interactions/) | 22 |+| 05 | [Text & Typography](animations/05-text-typography/) | 14 |+| 06 | [3D & Advanced](animations/06-3d-advanced/) | 17 |+| 07 | [Ambient & Background](animations/07-ambient-background/) | 15 |## What's inside each entrydiff --git a/animations/01-scroll-based/README.md b/animations/01-scroll-based/README.mdindex 1a7159d5..f5a9d9b8 100644--- a/animations/01-scroll-based/README.md+++ b/animations/01-scroll-based/README.md@@ -42,3 +42,5 @@ Techniques driven by scroll position.z-index stacking; a scale-down on the receding layer adds depth to the transition.- [Zoom Into Image](zoom-into-image/) — clip-path expands from a framed card to full-bleedas you scroll; the portal effect is clip-path: inset() collapsing from center outward.+- [Scroll Image Sequence](scroll-image-sequence/) — a canvas pinned with position:sticky while+ scroll progress maps to a frame index; the Apple product-scroll technique, frames drawn procedurally.diff --git a/animations/01-scroll-based/reveal-on-scroll/README.md b/animations/01-scroll-based/reveal-on-scroll/README.mdnew file mode 100644index 00000000..972b13f7--- /dev/null+++ b/animations/01-scroll-based/reveal-on-scroll/README.md@@ -0,0 +1,52 @@+# Reveal on Scroll++## What it is+A reveal-on-scroll animation holds an element in a hidden pre-state — faded, offset, scaled, blurred, or clipped — until it crosses a trigger line inside the viewport, then transitions it to its resting state. An `IntersectionObserver` watches each element and fires a single callback the moment it enters, so nothing runs on every scroll frame. This demo collects seven interchangeable reveal techniques behind one observer.++## When to use it+- Progressively disclosing content sections, cards, or media as a long page scrolls+- Drawing the eye to a specific block when it first appears+- Landing pages where each section should feel deliberate rather than pre-rendered+- Any list where a lightweight reveal is preferable to running scroll math in JavaScript++## How it works+Each card carries a `data-fx` attribute naming its technique. CSS defines the hidden state per technique and a shared `.revealed` state; the observer only toggles the class. The trigger position is turned into a negative `rootMargin` on the bottom edge, which pulls the observer's boundary up to match the dashed line:++```js+const margin = -(100 - threshold); // threshold 70 → -30+observer = new IntersectionObserver(entries => {+ entries.forEach(e => {+ const fx = e.target.dataset.fx;+ if (e.isIntersecting) {+ reveal(e.target, fx, i);+ if (!repeatTog.checked) observer.unobserve(e.target); // fire once+ } else if (repeatTog.checked) {+ hide(e.target, fx, i); // re-arm on exit+ }+ });+}, { root: stage, rootMargin: `0px 0px ${margin}% 0px`, threshold: 0 });+```++The pre-states live entirely in CSS — for example `[data-fx="blur"]{opacity:0;filter:blur(12px)}` becoming `.revealed[data-fx="blur"]{opacity:1;filter:blur(0)}`. The `stagger` technique is the exception: its child chips are advanced with per-index `setTimeout` delays so they cascade rather than reveal together.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Trigger position | 70% | Where the dashed line sits; higher = element must scroll further before firing |+| `rootMargin` | `0 0 -30% 0` | Derived from trigger; shrinks the observer's active area from the bottom |+| `threshold` | 0 | Fires as soon as any pixel crosses; raise to require a fraction of the element visible |+| Repeat on re-enter | off | When off, `unobserve` fires each reveal once; when on, elements re-hide on exit |+| Transition duration | 0.6s | Per-technique CSS timing; the stagger group adds 80ms between children |++## Production notes+- **One observer, many elements**: a single `IntersectionObserver` handling every card is far cheaper than a `scroll` listener recomputing positions. The observer runs off the main thread.+- **Fire-once vs. replay**: calling `unobserve` after the first intersection is the common production choice — it prevents re-animation on scroll-up and releases the element. Keep observing only if you genuinely want a repeating effect.+- **`rootMargin` units**: percentages are relative to the root's size. Negative bottom margin is the standard trick for "trigger when the element is N% up the viewport."+- **Reduced motion**: the demo disables transitions under `prefers-reduced-motion`, so content still appears — it just skips the movement. Never gate visibility on the animation completing.+- **Library equivalents**: GSAP ScrollTrigger's `toggleActions` and AOS (Animate On Scroll) wrap this exact pattern; Framer Motion's `whileInView` prop is the React equivalent and uses `IntersectionObserver` underneath.++## See also+- [Stagger Reveal](../stagger-reveal/) — cascading the reveal across a group of siblings+- [Scroll Trigger](../scroll-trigger/) — firing discrete actions at scroll positions+- [Fly In / Fly Out Contact List](../fly-in-fly-out-contact-list/) — reveal paired with an exit animation+- [Scrollytelling](../scrollytelling/) — continuous scroll-driven narrative instead of discrete triggersdiff --git a/animations/01-scroll-based/scroll-image-sequence/README.md b/animations/01-scroll-based/scroll-image-sequence/README.mdnew file mode 100644index 00000000..b3f4a6b5--- /dev/null+++ b/animations/01-scroll-based/scroll-image-sequence/README.md@@ -0,0 +1,56 @@+# Scroll Image Sequence++## What it is+A scroll image sequence pins a `<canvas>` to the viewport and maps scroll progress to a frame index — as you scroll, the "playhead" advances through a series of frames and each one is drawn to the canvas. Popularised by Apple's product pages, it turns a scroll gesture into a scrubbable video. Because the mapping is deterministic (a given scroll position always resolves to the same frame), scrubbing backward reverses the animation exactly.++## When to use it+- Product reveals where a physical object rotates or disassembles as the user scrolls+- Turning a short pre-rendered 3D animation into an interactive, scroll-scrubbed hero+- Onboarding or explainer sections where scroll pace equals playback pace+- Any "cinematic" scroll moment where you want frame-accurate control instead of CSS transitions++## How it works+A tall track element provides the scroll budget; a child pins itself with `position: sticky`. On every scroll event you convert the track's position into a `0 → 1` progress value, multiply by the frame count, and draw that frame. This demo has no image assets, so each frame is generated procedurally — but the scrubbing logic is identical to the production version.++```js+function updateTarget(){+ const rect = track.getBoundingClientRect();+ const span = rect.height - innerHeight;+ const p = span > 0 ? Math.min(Math.max(-rect.top / span, 0), 1) : 0;+ targetFrame = p * (TOTAL - 1);+}+addEventListener('scroll', updateTarget, {passive:true}); // fires for wheel AND touch+```++The render loop either snaps to the target frame or eases toward it (the smoothing toggle):++```js+if (smoothing) shownFrame += (targetFrame - shownFrame) * 0.18; // lerp+else shownFrame = targetFrame; // snap+drawFrame(Math.round(shownFrame));+```++`drawFrame(index)` is a pure function of the index — same index, same picture — which is exactly why reverse scrubbing rewinds cleanly.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Total frames | 120 | More frames = smoother scrub but more images to preload in production |+| Smoothing (lerp) | on | Eases `shownFrame` toward the scroll target; off = hard snap per frame |+| Lerp factor | 0.18 | Higher catches up faster; lower adds more inertia/lag |+| Track height | 340vh | The scroll distance budget — longer track = slower, more deliberate scrub |+| Sticky pin | `top: 0` | Where the canvas locks in the viewport during the scrub |++## Production notes+- **Preload every frame.** The real technique loads an array of `Image` objects (a video exported to a numbered JPG/WebP sequence). Never fetch frames on demand — decode stalls cause visible gaps. Kick off preloading before the section scrolls into view and show a loader until it's ready.+- **Frame count vs. weight.** 120–300 frames at full width is a lot of bytes. Use WebP/AVIF, cap the longest edge to the display size, and consider a lower frame count on mobile.+- **Draw the nearest frame, don't animate the canvas.** You are replacing the whole canvas each scroll tick; there is no CSS transition involved. Smoothing is done by easing the *frame index*, not by transitioning pixels.+- **`will-change` / decode.** Call `img.decode()` after load so the first paint of each frame isn't a jank spike. Keep the canvas sized to device pixels via `devicePixelRatio` (clamped) to avoid over-drawing on high-DPI phones.+- **Touch scroll works for free** because the effect is driven by the `scroll` event, not `wheel`. Avoid `preventDefault` scroll-hijacking libraries unless you need them.+- **Library equivalents:** GSAP **ScrollTrigger** with a `scrub` tween over a frame-index object is the canonical implementation; pair it with **Lenis** (or GSAP ScrollSmoother) for inertial smoothing. `<canvas>` + a preloaded frame array is the same idea without dependencies.++## See also+- [Scrub Animation](../scrub-animation/) — welding transforms directly to scroll position+- [Pin Animation](../pin-animation/) — the `position: sticky` pinning this technique relies on+- [Sticky Section](../sticky-section/) — a full section pinned while its interior scrubs+- [Zoom Into Image](../zoom-into-image/) — another scroll-scrubbed reveal effectdiff --git a/animations/01-scroll-based/scroll-image-sequence/index.html b/animations/01-scroll-based/scroll-image-sequence/index.htmlnew file mode 100644index 00000000..7f2bc8cf--- /dev/null+++ b/animations/01-scroll-based/scroll-image-sequence/index.html@@ -0,0 +1,169 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Scroll Image Sequence</title>+ <style>+ :root{+ --bg:#0b0b0d;--stage:#04060c;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);+ --accent:#58a6ff;--text:#f4f4f2;--muted:#77777e;+ --mono:ui-monospace,Menlo,Consolas,monospace;+ }+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--text);font-family:var(--mono);-webkit-font-smoothing:antialiased}+ header{padding:clamp(14px,3vw,24px)}+ header h1{font-size:clamp(18px,3vw,26px);letter-spacing:-.02em}+ header p{font-size:clamp(11px,1.4vw,13px);color:var(--muted);margin-top:6px;max-width:60ch}+ /* Tall track gives the scroll budget; the inner panel pins with position:sticky. */+ .track{position:relative;height:340vh}+ .pin{position:sticky;top:0;height:100vh;display:flex;flex-direction:column;padding:clamp(10px,2vw,18px);gap:12px}+ .stage{flex:1;min-height:0;position:relative;border:1px solid var(--ui-border);border-radius:10px;background:var(--stage);overflow:hidden}+ canvas{display:block;width:100%;height:100%}+ .hud{position:absolute;top:12px;left:12px;font-size:11px;letter-spacing:1px;color:var(--muted);pointer-events:none}+ .hud .fr{color:var(--accent);font-size:clamp(15px,2.4vw,20px);letter-spacing:.03em}+ .hint{position:absolute;bottom:12px;left:0;right:0;text-align:center;font-size:11px;letter-spacing:2px;text-transform:uppercase;color:var(--muted);pointer-events:none}+ .hint.hide{opacity:0;transition:opacity .4s}+ .bar{position:absolute;left:0;right:0;bottom:0;height:3px;background:rgba(255,255,255,.06)}+ .bar i{display:block;height:100%;background:var(--accent);transform-origin:left;transform:scaleX(0)}+ /* Controls sit inside the pinned viewport so they stay reachable while scrubbing. */+ aside{background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:10px;padding:12px 14px;+ display:flex;gap:clamp(12px,3vw,28px);align-items:center;flex-wrap:wrap}+ .ctl{display:flex;flex-direction:column;gap:4px;flex:1;min-width:150px}+ .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--accent)}+ .row{display:flex;align-items:center;gap:8px}+ input[type=range]{flex:1;accent-color:var(--accent);min-height:44px}+ .sv{width:52px;text-align:right;font-size:12px}+ .tog{display:flex;align-items:center;gap:8px;font-size:11px;cursor:pointer;min-height:44px;user-select:none}+ .tog input{accent-color:var(--accent);width:18px;height:18px;flex-shrink:0}+ .note{font-size:10px;color:var(--muted);line-height:1.5;flex-basis:100%}+ @media(max-width:600px){+ aside{flex-direction:column;align-items:stretch}+ .ctl{min-width:0}+ }+ @media(prefers-reduced-motion:reduce){.hint{transition:none}}+ </style>+</head>+<body>+<header>+ <h1>Scroll Image Sequence</h1>+ <p>The Apple product-scroll technique: a canvas pinned with position:sticky while scroll progress maps to a frame index that gets drawn — scrub back and it reverses perfectly.</p>+</header>++<div class="track" id="track">+ <div class="pin">+ <div class="stage">+ <canvas id="c"></canvas>+ <div class="hud"><div class="fr"><span id="frameNo">000</span> / <span id="frameTot">120</span></div>PROCEDURAL FRAME</div>+ <div class="hint" id="hint">Scroll to scrub ⇅</div>+ <div class="bar"><i id="barFill"></i></div>+ </div>+ <aside>+ <div class="ctl">+ <span class="lbl">Total frames</span>+ <div class="row"><input type="range" id="frames" min="24" max="240" step="1" value="120"><span class="sv" id="framesV">120</span></div>+ </div>+ <label class="tog"><input type="checkbox" id="smooth" checked> Smoothing (lerp between frames)</label>+ <p class="note">Real deployments preload an array of image frames (an exported video → JPG sequence) and draw the nearest one per scroll frame. This demo generates each frame procedurally — a rotating wireframe object — so it stays dependency-free and offline.</p>+ </aside>+ </div>+</div>++<script>+const canvas=document.getElementById('c'),ctx=canvas.getContext('2d');+const track=document.getElementById('track');+const framesEl=document.getElementById('frames'),framesV=document.getElementById('framesV');+const smoothEl=document.getElementById('smooth');+const frameNo=document.getElementById('frameNo'),frameTot=document.getElementById('frameTot');+const barFill=document.getElementById('barFill'),hint=document.getElementById('hint');+const reduce=matchMedia('(prefers-reduced-motion:reduce)').matches;++let TOTAL=+framesEl.value; // total "images" in the sequence+let targetFrame=0; // frame the scroll position points at+let shownFrame=0; // frame currently drawn (lerps toward target)+let W=0,H=0,DPR=1;++// --- Geometry: a cube + an inner octahedron, both wireframe -----------------+const CUBE_V=[[-1,-1,-1],[1,-1,-1],[1,1,-1],[-1,1,-1],[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]];+const CUBE_E=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]];+const OCT_V=[[1.4,0,0],[-1.4,0,0],[0,1.4,0],[0,-1.4,0],[0,0,1.4],[0,0,-1.4]];+const OCT_E=[[0,2],[0,3],[0,4],[0,5],[1,2],[1,3],[1,4],[1,5],[2,4],[2,5],[3,4],[3,5]];++function resize(){+ DPR=Math.min(devicePixelRatio||1,2);+ const r=canvas.getBoundingClientRect();+ W=r.width;H=r.height;+ canvas.width=Math.round(W*DPR);canvas.height=Math.round(H*DPR);+ ctx.setTransform(DPR,0,0,DPR,0,0);+}+function rotate(v,ax,ay){+ let [x,y,z]=v;+ const cy=Math.cos(ay),sy=Math.sin(ay);+ const x1=x*cy-z*sy, z1=x*sy+z*cy;+ const cx=Math.cos(ax),sx=Math.sin(ax);+ const y1=y*cx-z1*sx, z2=y*sx+z1*cx;+ return [x1,y1,z2];+}+function project(v,cx,cy,s){+ const d=4.5, k=d/(d-v[2]); // simple perspective divide+ return [cx+v[0]*s*k, cy+v[1]*s*k, v[2]];+}+function drawShape(verts,edges,rx,ry,explode,cx,cy,s){+ const p=verts.map(v=>{+ const n=Math.hypot(v[0],v[1],v[2])||1;+ const ex=[v[0]+v[0]/n*explode, v[1]+v[1]/n*explode, v[2]+v[2]/n*explode]; // push out along its own direction+ return project(rotate(ex,rx,ry),cx,cy,s);+ });+ for(const [a,b] of edges){+ const za=(p[a][2]+p[b][2])/2; // depth for shading+ const alpha=0.28+0.62*((za+2.2)/4.4);+ ctx.strokeStyle='rgba(88,166,255,'+alpha.toFixed(3)+')';+ ctx.lineWidth=1.4;+ ctx.beginPath();ctx.moveTo(p[a][0],p[a][1]);ctx.lineTo(p[b][0],p[b][1]);ctx.stroke();+ }+ ctx.fillStyle='#cfe3ff';+ for(const q of p){ctx.beginPath();ctx.arc(q[0],q[1],1.8,0,7);ctx.fill();}+}+// Draw one procedural "image" for a given frame index. Deterministic: same+// frame index always yields the same picture, so scrubbing reverses exactly.+function drawFrame(f){+ const t=TOTAL>1?f/(TOTAL-1):0; // 0..1 through the sequence+ ctx.clearRect(0,0,W,H);+ const cx=W/2, cy=H/2, s=Math.min(W,H)*0.24;+ const ry=t*Math.PI*3, rx=t*Math.PI*1.5;+ const explode=Math.sin(t*Math.PI)*0.9; // implode → explode → implode+ drawShape(CUBE_V,CUBE_E,rx,ry,explode,cx,cy,s);+ drawShape(OCT_V,OCT_E,-rx*1.3,-ry*0.7,explode*0.5,cx,cy,s*0.62);+}++function updateTarget(){+ const rect=track.getBoundingClientRect();+ const span=rect.height-innerHeight;+ const p=span>0?Math.min(Math.max(-rect.top/span,0),1):0;+ targetFrame=p*(TOTAL-1);+ barFill.style.transform='scaleX('+p+')';+ if(p>0.02) hint.classList.add('hide');+}++let raf=null;+function loop(){+ const smoothing=smoothEl.checked&&!reduce;+ if(smoothing) shownFrame+=(targetFrame-shownFrame)*0.18;+ else shownFrame=targetFrame;+ const idx=Math.round(shownFrame);+ drawFrame(idx);+ frameNo.textContent=String(idx).padStart(3,'0');+ raf=requestAnimationFrame(loop);+}++framesEl.addEventListener('input',e=>{+ TOTAL=+e.target.value;framesV.textContent=TOTAL;frameTot.textContent=TOTAL;+ updateTarget();+});+addEventListener('scroll',updateTarget,{passive:true}); // scroll fires for wheel AND touch+addEventListener('resize',()=>{resize();updateTarget();});++resize();updateTarget();shownFrame=targetFrame;loop();+</script>+</body>+</html>diff --git a/animations/01-scroll-based/scrollytelling/README.md b/animations/01-scroll-based/scrollytelling/README.mdnew file mode 100644index 00000000..c2cae987--- /dev/null+++ b/animations/01-scroll-based/scrollytelling/README.md@@ -0,0 +1,47 @@+# Scrollytelling++## What it is+Scrollytelling binds a narrative to the scroll position, so that advancing through text chapters continuously drives a synchronized visual. Rather than snapping between discrete states, it computes a fractional progress value and interpolates every visual property from it — the reader experiences one continuous journey, not a slideshow. This demo descends through six ocean depth zones, crossfading a porthole's water color and counting metres as you scroll.++## When to use it+- Data-driven stories where a chart, map, or diagram should evolve as the reader progresses+- Explainer content that pairs a sticky visual with scrolling prose ("scrollytelling" journalism)+- Product walkthroughs where a single hero element morphs across feature descriptions+- Any narrative where the transition *between* points carries as much meaning as the points themselves++## How it works+A sticky visual column stays pinned while text chapters scroll past it. On each frame the code finds which chapter has crossed the reading line (42% down the stage), then derives a fractional index — the integer part is the current chapter, the decimal is progress toward the next. Every visual value is a `lerp` across that fraction:++```js+frac = clamp(frac, 0, N - 0.001);+const ci = Math.floor(frac), cf = frac - ci; // chapter index + fraction+const c = CHS[ci], cn = CHS[Math.min(ci + 1, N - 1)];+const col = lerpCol(c.ac, cn.ac, cf); // accent color blend+depNum.textContent = Math.round(lerp(c.depth, cn.depth, cf)).toLocaleString();+phBg.style.background = `radial-gradient(circle at 50% 40%, ${lerpCol(c.bg, cn.bg, cf)}, #000 80%)`;+porthole.style.borderColor = col;+```++Reads are throttled with a `requestAnimationFrame` gate (`ticking`) so the scroll handler never does layout work more than once per frame. Because the depth number and colors are interpolated rather than switched, the descent reads as continuous — 0 to 10,935 metres flows without jumps.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Reading line | 0.42 × stage height | Where a chapter is considered "active"; lower = triggers later |+| Chapter min-height | 0.9 × stage height | Scroll distance per chapter; taller = slower, more granular transitions |+| Fraction `cf` | derived | Drives every crossfade; 0 at chapter start, approaches 1 at the next boundary |+| rAF gate | on | Coalesces scroll events to one update per frame |++## Production notes+- **Fractional, not stepped**: the value that makes scrollytelling feel smooth is the decimal progress between chapters. If you only switch on integer chapter changes, you get a slideshow — interpolate everything you can.+- **Sticky visual, scrolling text**: the pattern is a `position: sticky` visual beside taller text columns. This is cheaper and more robust than JS-pinning; let CSS hold the visual in place.+- **Throttle reads**: `getBoundingClientRect` in a scroll handler forces layout. The rAF gate here keeps that to once per frame; on heavier visuals, cache rects and only recompute on resize.+- **Color interpolation**: blending hex colors requires parsing to RGB channels and lerping each — CSS won't tween `background` mid-value on its own, which is why this is done in JS.+- **Reduced motion**: the demo drops the porthole's `transition` under `prefers-reduced-motion`; content and depth still update, just without the eased color fade.+- **Library equivalents**: Scrollama is the standard vanilla library for the "sticky graphic + scrolling steps" layout; GSAP ScrollTrigger with `scrub` handles the interpolation; Framer Motion's `useScroll` + `useTransform` map scroll progress to any animated value in React.++## See also+- [Sticky Section](../sticky-section/) — pinning a section and scrubbing through internal states+- [Scrub Animation](../scrub-animation/) — tying an animation's timeline directly to scroll+- [Reveal on Scroll](../reveal-on-scroll/) — discrete triggers instead of continuous progress+- [Progress Bar](../progress-bar/) — surfacing scroll progress as a readoutdiff --git a/animations/01-scroll-based/section-wipe/README.md b/animations/01-scroll-based/section-wipe/README.mdnew file mode 100644index 00000000..4b40bc4d--- /dev/null+++ b/animations/01-scroll-based/section-wipe/README.md@@ -0,0 +1,47 @@+# Section Wipe++## What it is+A section wipe is a transition where the next section slides up over the current one as you scroll, rather than the current one scrolling away. It is built almost entirely from layout: each section is `position: sticky` at the top with an ascending `z-index`, so a higher-numbered section naturally rises over its predecessor. This demo stacks four full-height sections and adds a single JavaScript touch — the outgoing section scales down slightly as it's covered.++## When to use it+- Full-screen storytelling sections that should feel layered rather than scrolled+- Landing pages where each section is a distinct "screen" that replaces the last+- Portfolio or case-study layouts with strong section-to-section breaks+- Anywhere the covering motion should read as depth, one panel sliding behind another++## How it works+The wipe itself requires no animation code: every `.section` is `position: sticky; top: 0; height: 100%` of the stage, and their `z-index` values ascend (1, 2, 3, 4). As you scroll, each section sticks at the top until the next one — being higher in the stack — covers it. The only scripted effect is the receding scale, computed from how much of the viewport the next section has already covered:++```js+sections.forEach((s, i) => {+ if (i === sections.length - 1) return; // top section never recedes+ const nextR = sections[i + 1].getBoundingClientRect();+ const coverage = sr.height - (nextR.top - sr.top); // px of this section covered+ const t = clamp(coverage / (sr.height * wipeRange), 0, 1);+ contents[i].style.transform = `scale(${lerp(1, scaleFloor, t).toFixed(4)})`;+});+```++Because `t` is a continuous ratio of coverage, the scale is scrubbed to scroll — freeze mid-wipe and the section sits at an intermediate scale, no snap. The scale-down makes the covered section feel like it's sliding *behind* the incoming one rather than simply being hidden.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| `z-index` order | ascending 1→4 | Determines stacking; higher sections wipe over lower ones |+| Scale floor | 0.96 | How far the outgoing section shrinks; lower = deeper recede |+| Wipe range | 100% | Fraction of coverage over which the scale completes; lower = finishes sooner |+| Coverage `t` | derived | 0 when the next section is off-stage, 1 when it fully covers |++## Production notes+- **The wipe is free**: sticky positioning plus ascending `z-index` produces the entire covering motion with zero JavaScript. Reach for script only for embellishments like the scale, never for the wipe itself.+- **Scale the content, not the section**: the transform is applied to `.sec-content` inside the sticky section, not the sticky element — transforming a sticky element can break its stickiness in some engines.+- **`will-change: transform`**: set on the scaled content so the browser promotes it to its own layer; the demo drops it under reduced motion to avoid holding a needless layer.+- **Guard the top section**: the last section has the highest `z-index` and is never covered, so it's skipped in the scale loop — it should stay at scale 1.+- **Reduced motion**: when `prefers-reduced-motion` is set the scale loop is skipped entirely; sections still wipe (that's pure layout) but without the recede.+- **Library equivalents**: GSAP ScrollTrigger with `scrub: true` on a scale tween implements the same recede and adds the easing CSS alone can't provide here; Framer Motion maps `useScroll` progress to a `scale` motion value for the React version.++## See also+- [Sticky Section](../sticky-section/) — pinning one section and morphing its interior+- [Stacking Cards](../stacking-cards/) — sticky stacking applied to cards rather than sections+- [Cover Card to Fixed Header](../cover-card-to-fixed-header/) — a sticky element transforming as it's passed+- [Snap Scrolling](../snap-scrolling/) — snapping between full-height sectionsdiff --git a/animations/01-scroll-based/stagger-reveal/README.md b/animations/01-scroll-based/stagger-reveal/README.mdnew file mode 100644index 00000000..489a0119--- /dev/null+++ b/animations/01-scroll-based/stagger-reveal/README.md@@ -0,0 +1,55 @@+# Stagger Reveal++## What it is+A stagger reveal animates a group of sibling elements with the same transition but offset start times, so they cascade in sequence rather than appearing at once. The delay between items — and the order they fire in — is what turns a flat group into a readable sweep. This demo reveals a card grid, a list, and a chip cluster when each scrolls into view, with switchable forward, reverse, center-out, and random ordering.++## When to use it+- Card grids, search results, or gallery tiles that should feel populated rather than dumped+- Navigation menus and dropdowns opening their items in sequence+- List rows or table content entering after a section reveal+- Any group where a uniform simultaneous appearance feels abrupt or mechanical++## How it works+Each item shares one CSS transition (`opacity` and `translateY`) and starts hidden. An `IntersectionObserver` on each section triggers `staggerIn`, which computes an order array for the chosen direction and schedules each item's `.in` class with a delay of `orderIndex × staggerMs`:++```js+function getOrder(n) {+ if (direction === 'forward') return Array.from({length: n}, (_, i) => i);+ if (direction === 'reverse') return Array.from({length: n}, (_, i) => n - 1 - i);+ if (direction === 'center') { const c = Math.floor(n / 2);+ return Array.from({length: n}, (_, i) => Math.abs(i - c)); } // center-out+ // random: Fisher–Yates shuffle+}++function staggerIn(items) {+ const order = getOrder(items.length);+ items.forEach((el, i) => {+ setTimeout(() => el.classList.add('in'), order[i] * staggerMs);+ });+}+```++The order array holds a *rank* per item, not a target — item `i` waits `order[i] × staggerMs`. Center-out works by using distance-from-center as the rank, so the middle items (rank 0) fire first. The side panel's preview matrix renders those same ranks as numbered, brightness-coded dots so the cascade is legible before you scroll.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Stagger delay | 50ms | Gap between consecutive items; 40–60ms is the sweet spot |+| Direction | forward | Order the ranks are assigned: forward, reverse, center-out, random |+| Item transition | 0.4s | Per-item animation duration, independent of the stagger gap |+| Observer threshold | 0.05 | Fraction of the section visible before the group fires |+| Total stagger budget | — | delay × item count; keep under ~600ms so late items don't lag |++## Production notes+- **Delay vs. duration**: the stagger delay is the gap between items; each item's own transition duration is separate. Both matter — a 50ms stagger with a 400ms transition means the group overlaps heavily, which usually looks best.+- **Cap the total**: on long lists, `delay × count` grows without bound and the tail feels sluggish. Clamp the effective delay so the whole cascade lands in ~600ms regardless of item count.+- **Below 30ms reads as simultaneous**: if the eye can't separate the items, you've paid for stagger and gotten none of its benefit. Above ~100ms it starts to drag.+- **`setTimeout` vs. CSS `transition-delay`**: this demo uses timers so direction can change at runtime; a static cascade can instead set `transition-delay: calc(var(--i) * 50ms)` per item and avoid JS entirely.+- **Reduced motion**: transitions are disabled under `prefers-reduced-motion`, so items appear immediately — the stagger is decorative, never load-bearing.+- **Library equivalents**: GSAP's `stagger` property (including `from: "center"` and `"random"`) is the direct analog; Framer Motion uses `staggerChildren` on a parent variant; Motion One exposes a `stagger()` helper.++## See also+- [Reveal on Scroll](../reveal-on-scroll/) — the single-element reveal this cascades+- [Fly In / Fly Out Contact List](../fly-in-fly-out-contact-list/) — staggered list entrance and exit+- [Stacking Cards](../stacking-cards/) — sequenced cards driven by scroll position+- [Snap Scrolling](../snap-scrolling/) — another way to pace a group through the viewportdiff --git a/animations/01-scroll-based/sticky-section/README.md b/animations/01-scroll-based/sticky-section/README.mdnew file mode 100644index 00000000..2800e103--- /dev/null+++ b/animations/01-scroll-based/sticky-section/README.md@@ -0,0 +1,50 @@+# Sticky Section++## What it is+A sticky section pins an entire section to the viewport for an extended scroll distance while its interior morphs through a sequence of states. The pin is created with `position: sticky` inside a tall wrapper; scroll position within that wrapper becomes a 0–1 timeline that the contents are scrubbed against. This demo holds a two-column section in place and cycles it through four labelled states, with a segmented progress readout.++## When to use it+- Multi-step explanations where one frame should stay put while its content advances+- Feature tours that swap illustration and copy without the viewport moving+- Product pages that "hold" a hero while walking through its states+- Any sequence where pinning the frame keeps the reader oriented better than scrolling new sections in++## How it works+The wrapper is four stage-heights tall; the inner section is `position: sticky; top: 0`, so it stays fixed while the wrapper scrolls past. Progress is `(scrollTop − pinStart) / (pinHeight − stageHeight)`, clamped to 0–1. Multiplying by the state count gives the active state index and the fraction within it:++```js+const pinStart = wrap.offsetTop, pinH = wrap.offsetHeight;+const p = clamp((st - pinStart) / (pinH - stageH), 0, 1); // 0..1 while pinned+const si = Math.min(Math.floor(p * 4), 3), sf = p * 4 - si; // state index + fraction++states.forEach((s, i) => s.classList.toggle('visible', i === si));+illus.forEach((il, i) => il.classList.toggle('visible', i === si));+for (let i = 0; i < 4; i++) { // segmented progress+ const bar = document.getElementById('sg' + i);+ bar.style.width = i < si ? '100%' : i === si ? Math.round(sf * 100) + '%' : '0%';+}+```++The three lifecycle phases — `approaching`, `stuck`, `released` — come from comparing `scrollTop` against the pin's start and end. States themselves crossfade via a CSS `opacity` transition on `.visible`; only the segment bars use the raw fraction, so the section reads as pinned frames advancing rather than a continuous scrub.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Wrapper height | 4 × stage height | Total scroll budget; more height = slower state changes |+| State count | 4 | `p × count` maps progress to states; each owns `1 / count` of the range |+| Progress `p` | derived | 0 at pin start, 1 when the pin releases |+| State transition | 0.5s opacity | Crossfade between states; illustration column uses 0.6s |++## Production notes+- **Pins the section, not one element**: this is the key distinction from pin-animation. Here the whole section sticks and its *contents* change; a pin-animation pins one element while siblings scroll past it.+- **Height defines the budget**: the amount of scroll the pin lasts is set entirely by the wrapper's height. Want a longer sequence? Make the wrapper taller — no JS change needed.+- **Sticky beats JS pinning**: `position: sticky` is handled by the browser's compositor and won't jitter the way `position: fixed` toggling in a scroll handler can. Reserve JS for reading progress, not for holding the element.+- **State boundaries are thresholds, not events**: because the state index comes from `floor(p × count)`, crossing a boundary is just the fraction rolling over — no discrete event to miss if a scroll frame is dropped.+- **Reduced motion**: state and illustration transitions are disabled under `prefers-reduced-motion`; the content still switches, it just cuts instead of fades.+- **Library equivalents**: GSAP ScrollTrigger with `pin: true` and a `scrub` timeline is the production-grade version and adds easing across states; Framer Motion pairs a sticky wrapper with `useScroll({ offset })` to derive the same progress value.++## See also+- [Pin Animation](../pin-animation/) — pinning a single element while siblings pass+- [Scrub Animation](../scrub-animation/) — tying a timeline continuously to scroll+- [Scrollytelling](../scrollytelling/) — a sticky visual driven by scrolling narrative+- [Section Wipe](../section-wipe/) — stacked sticky sections that cover one anotherdiff --git a/animations/01-scroll-based/zoom-into-image/README.md b/animations/01-scroll-based/zoom-into-image/README.mdnew file mode 100644index 00000000..872ac1e5--- /dev/null+++ b/animations/01-scroll-based/zoom-into-image/README.md@@ -0,0 +1,51 @@+# Zoom Into Image++## What it is+A zoom-into-image effect expands a framed image outward to full-bleed as you scroll, reading as a camera flying into the picture — the "portal" effect. It's driven not by scaling the image but by animating a `clip-path: inset()` from a large inset down to zero, so a small windowed crop grows to fill the stage. This demo pins a nighttime landscape in a sticky frame and opens the clip as you scroll through a fixed budget, revealing a caption near the end.++## When to use it+- Hero-to-content transitions where a preview card should open into an immersive image+- Editorial or gallery intros that "enter" a featured photograph+- Section breaks that use a single image as a portal between two parts of a page+- Any moment where you want the sense of moving *into* an image rather than past it++## How it works+The image sits in a `position: sticky` container inside a tall section, giving a scroll budget. Progress across that budget is a 0–1 value; the inset percentage and corner radius are both `lerp`ed from their start values down to zero, so the crop expands and its rounded frame squares off simultaneously:++```js+const pinStart = zoomSec.offsetTop, budget = zoomSec.offsetHeight - stageH;+const p = clamp((st - pinStart) / budget, 0, 1);+const inset = lerp(startPct, 0, p); // 30% → 0% (crop opens)+const radius = lerp(brStart, 0, p); // 16px → 0 (corners square off)++zoomImg.style.clipPath = portalTog.checked+ ? `inset(${inset.toFixed(2)}% round ${radius.toFixed(1)}px)`+ : `inset(${inset.toFixed(2)}%)`;++caption.style.opacity = p > 0.88 ? ((p - 0.88) / 0.12).toFixed(3) : '0';+```++Clipping rather than scaling is the crucial choice: `clip-path` reveals more of the *existing* image at full resolution, so nothing blurs or pixelates the way a `transform: scale()` zoom would. The caption fades in only over the final 12% of the scroll, once the image is essentially full-bleed.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Start size (inset) | 30% | Inset on each side at the start; 30% shows a 40%-wide crop |+| Border radius start | 16px | Corner rounding of the initial frame; lerps to 0 as it opens |+| Progress `p` | derived | 0 at pin start, 1 when the scroll budget is exhausted |+| Section height | 2.5 × stage | Scroll distance the zoom occupies; taller = slower open |+| Caption fade window | last 12% (p > 0.88) | When the caption overlay begins appearing |++## Production notes+- **Clip, don't scale**: `clip-path: inset()` reveals real pixels, keeping the image sharp at every step. A `scale()` zoom enlarges a fixed render and softens. Use clipping when the whole image is present and you're uncovering it.+- **`will-change: clip-path`**: set on the image so the browser prepares for the animating clip. Animating `clip-path` is compositor-friendly on modern engines but still benefits from the hint.+- **Sticky provides the pin**: the image holds still via `position: sticky` while the tall section scrolls; the clip is the only thing changing, which keeps the effect cheap.+- **`round` keyword**: `inset(x% round Ypx)` combines the crop and rounded corners in one property, so both animate together off a single progress value.+- **Reduced motion**: under `prefers-reduced-motion` the CSS forces `clip-path: inset(0%)` and shows the caption immediately — the reader gets the final full image with no fly-in.+- **Library equivalents**: GSAP ScrollTrigger with `scrub` tweening `clipPath` is the direct equivalent and adds easing; Framer Motion animates the `clipPath` style off a `useTransform` of scroll progress in React.++## See also+- [Sticky Section](../sticky-section/) — the pinning mechanic this builds on+- [Scrub Animation](../scrub-animation/) — binding a property continuously to scroll+- [Cover Card to Fixed Header](../cover-card-to-fixed-header/) — a card transforming as it's scrolled+- [Parallax Depth of Field](../parallax-depth-of-field/) — another depth-through-scroll illusiondiff --git a/animations/02-entrance-and-exit/blur-in/README.md b/animations/02-entrance-and-exit/blur-in/README.mdnew file mode 100644index 00000000..6f9bf5a2--- /dev/null+++ b/animations/02-entrance-and-exit/blur-in/README.md@@ -0,0 +1,53 @@+# Blur In++## What it is+Blur In fades an element into view while transitioning it from a heavy blur to sharp focus, mimicking a camera pulling focus onto a subject. The simultaneous rise in opacity and drop in blur radius reads as cinematic because it echoes how real optics resolve an image, rather than the flat cross-fade of a plain opacity transition.++## When to use it+- Hero cards, modals, and single focal elements entering a view+- Photography, film, and portfolio sites where the camera metaphor fits the brand+- Drawing attention to one arriving element, not a grid or list of them+- Paired with a small upward translate for a subtle "settling into place" feel++## How it works+Three properties transition together on the same duration and easing: `opacity` from 0 to 1, `filter: blur()` from a large radius to zero, and an optional `translateY`. The blurred start state lives on the base `.card` rule; adding `.in` resolves all three at once:++```css+.card{+ opacity:0;filter:blur(var(--blur-start));transform:translateY(var(--ty));+ transition:opacity var(--dur) var(--ease),+ filter var(--dur) var(--ease),+ transform var(--dur) var(--ease);+ will-change:opacity,filter,transform}+.card.in{opacity:1;filter:blur(0);transform:translateY(0)}+```++Toggling in JS is just a class flip after forcing a reflow so the transition restarts cleanly:++```js+card.classList.remove('in');void card.offsetWidth;+card.classList.add('in');+```++The blur-only and fade-only modes exist to show that the two channels are separable — blur alone feels like focus without arrival, fade alone is the ordinary transition. Combined, they read as a lens finding its subject.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Starting blur (`--blur-start`) | 20px | Higher = more dramatic focus pull; over ~30px starts to look like frosted glass |+| Duration (`--dur`) | 700ms | Blur benefits from a slower curve than a plain fade — the optics feel takes time |+| Easing (`--ease`) | Ease out | Deceleration mimics a lens settling; linear feels robotic |+| Upward translate (`--ty`) | -8px | Small `translateY` adds a sense of the element rising into focus |++## Production notes+- **GPU cost**: `filter: blur()` is one of the more expensive properties to animate. It forces the element onto its own compositor layer and re-rasterizes each frame. Limit blur-in to a single hero element or a small group — never a long list, and be cautious on low-end mobile.+- **`will-change`**: declaring `will-change:filter` promotes the layer ahead of time and smooths the first frame, but leaving it on permanently wastes memory. Add it before the animation, remove it after if the element is long-lived.+- **Reduced motion**: the demo drops to a plain 300ms linear opacity fade with no blur or transform when `prefers-reduced-motion` is set — blur can be nauseating for motion-sensitive users.+- **Text blur pitfall**: blurring live text triggers subpixel re-rendering each frame and can look muddy mid-transition. Keep the end state at exactly `blur(0)` so the final frame is crisp.+- **Framer Motion**: animate `filter` between `"blur(20px)"` and `"blur(0px)"` alongside `opacity` in a variant.+- **Motion One / GSAP**: both animate the `filter` string directly; GSAP needs no plugin for CSS filters.++## See also+- [Fade In / Out](../fade-in-out/) — the opacity channel on its own+- [Scale In](../scale-in/) — another single-element focal entrance+- [Flip In](../flip-in/) — a more three-dimensional arrival for the same hero slotdiff --git a/animations/02-entrance-and-exit/bounce-in/README.md b/animations/02-entrance-and-exit/bounce-in/README.mdnew file mode 100644index 00000000..eb58c816--- /dev/null+++ b/animations/02-entrance-and-exit/bounce-in/README.md@@ -0,0 +1,52 @@+# Bounce In++## What it is+Bounce In brings an element up from small and low, overshoots its final size and position, then springs back to rest — the motion of something landing with momentum. Crucially, a real bounce is not a single easing curve: it is a series of hand-placed `@keyframes` waypoints, each defining an overshoot and settle, because one `cubic-bezier` can only overshoot once.++## When to use it+- Playful confirmations — a success badge, a "message sent" checkmark, an added-to-cart chip+- Toasts, tooltips, and popovers where a little life makes the appearance feel responsive+- Game UI, kids' products, and brands whose tone welcomes personality+- Any single element small enough that an energetic entrance won't feel heavy++## How it works+The card animates via a named keyframe rather than a transition. Each stop scales past 1 and pulls back under it, translating the vertical overshoot at the same time. The overshoot amounts are computed from an intensity slider so the waypoints stay proportional:++```js+const t=intensity/100;+const ov1=1+t*0.15,un1=1-t*0.07; // overshoot, then undershoot+kf=`@keyframes bounce-in{+ 0% {opacity:${fadeIn?0:1};transform:scale(0.3) translateY(40px)}+ 55% {opacity:1;transform:scale(${ov1.toFixed(3)}) translateY(-8px)}+ 80% {transform:scale(${un1.toFixed(3)}) translateY(3px)}+ 100%{opacity:1;transform:scale(1) translateY(0)}+}`;+```++```css+.card{opacity:0;transform:scale(0.3) translateY(40px)}+.card.in{animation:bounce-in var(--dur) ease forwards}+```++The generated CSS is injected into a live `<style>` tag, so changing intensity or bounce count rewrites the keyframe rule on the fly. Two- and three-bounce modes simply add more overshoot/undershoot pairs at tighter percentage intervals, each smaller than the last to imitate energy dissipating.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Overshoot intensity | 60% | Scales how far past 1.0 the waypoints reach; 0% = no bounce, 100% = exaggerated |+| Duration (`--dur`) | 1100ms | Bounces need room to breathe; too short and the springs read as a jitter |+| Bounces | 1 | Number of overshoot cycles — almost always 1; multiples look cartoonish |+| Combine with fade | on | Whether opacity starts at 0 or the element is already visible while it bounces |++## Production notes+- **Keyframes over easing**: an overshoot spring like `cubic-bezier(.34,1.56,.64,1)` gives *one* overshoot. Genuine multi-stage bounce and squash-and-stretch require explicit waypoints — that is the whole reason this technique uses `@keyframes`.+- **One bounce is usually right**: each extra bounce cycle reads as more juvenile. Reserve doubles and triples for deliberately toy-like contexts.+- **`animation-fill-mode: forwards`**: without it the element snaps back to its `scale(0.3)` start state after the animation ends; `forwards` holds the final frame.+- **Reduced motion**: the demo disables the keyframe animation entirely and shows the element at its resting state when `prefers-reduced-motion` is set — bounce is a classic motion-sickness trigger.+- **Framer Motion**: use a `type:"spring"` transition with `stiffness`/`damping`, or `bounce` on a spring — the physics model produces overshoot without authoring keyframes.+- **GSAP**: `Bounce.out` / `Elastic.out` eases, or a `.fromTo()` with overshoot values, cover this without a manual keyframe block.++## See also+- [Scale In](../scale-in/) — the same scale entrance without the overshoot+- [Rotate In](../rotate-in/) — pairs a springy ease with a spin for icons+- [Slide In](../slide-in/) — positional entrance that also benefits from spring easingdiff --git a/animations/02-entrance-and-exit/clip-path-reveal/README.md b/animations/02-entrance-and-exit/clip-path-reveal/README.mdnew file mode 100644index 00000000..6bdb76a7--- /dev/null+++ b/animations/02-entrance-and-exit/clip-path-reveal/README.md@@ -0,0 +1,58 @@+# Clip-Path Reveal++## What it is+A clip-path reveal uncovers an element by animating a mask shape from small (or edge-hidden) to fully open. The element is painted in full the entire time — only the visible region grows. Because nothing moves or fades, the content stays crisp and in place while a shape wipes across it, which is what gives the effect its cinematic, editorial feel.++## When to use it+- Image and media reveals on scroll (a photo wiped open left-to-right)+- Hero sections where a directional swipe uncovers the headline block+- Circular or "iris" reveals expanding from a click point+- Transitions between full-bleed panels where a shape mask replaces a crossfade++## How it works+The surface holds a start `clip-path` that hides it and transitions to an open one when `.in` is added. Both values live in CSS variables so the shape and direction controls can swap them:++```css+.surface {+ clip-path: var(--cp-out, inset(0 100% 0 0));+ transition: clip-path var(--dur) var(--ease);+ will-change: clip-path;+}+.surface.in { clip-path: var(--cp-in, inset(0 0% 0 0)); }+```++The demo keeps a lookup of shape/direction pairs — the `inset()` values wipe from an edge, while `circle()` and `ellipse()` grow a radius outward from center:++```js+const CLIPS = {+ inset: {+ left: { out: 'inset(0 100% 0 0)', in: 'inset(0 0% 0 0)' },+ right: { out: 'inset(0 0 0 100%)', in: 'inset(0 0 0 0%)' },+ center:{ out: 'inset(50% 50%)', in: 'inset(0%)' },+ },+ circle: { out: 'circle(0% at 50% 50%)', in: 'circle(75% at 50% 50%)' },+ ellipse: { out: 'ellipse(0% 0% at 50% 50%)', in: 'ellipse(80% 70% at 50% 50%)' },+ polygon: { out: 'polygon(0 0, 0 0, 0 100%, 0 100%)', in: 'polygon(0 0, 100% 0, 100% 100%, 0 100%)' },+};+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Shape | inset | `inset` (edge wipe), `circle` / `ellipse` (iris), `polygon` (angled swipe) |+| Direction | left | For `inset`, which edge the wipe travels from |+| Duration | 800ms | Reveals read best slower than a fade — the wipe needs to be seen |+| Easing | `cubic-bezier(.2,.7,.3,1)` | A smooth decel; the wipe eases to a stop rather than snapping |++## Production notes+- **Interpolate compatible shapes only.** CSS can animate `inset`→`inset`, `circle`→`circle`, or `polygon`→`polygon` (with the same vertex count), but it cannot tween *between* shape functions. Keep `out` and `in` the same function, as the demo does.+- **`clip-path` paints, it does not composite.** It is far cheaper than animating layout, but heavier than `opacity`/`transform`; on a huge full-screen element with a complex `polygon`, test on mobile and simplify the shape if frames drop.+- **Clipped content stays in the accessibility tree.** Unlike a curtain overlay, the text under a clip-path is still present and selectable throughout — good for SEO and screen readers, but it means the "hidden" content is not truly hidden from assistive tech.+- **Reduced motion:** the demo removes the clip animation under `prefers-reduced-motion` and falls back to an opacity fade, so no wipe plays.+- **Library equivalents:** GSAP `gsap.to(el, { clipPath: 'inset(0 0% 0 0)' })`; Framer Motion animate the `clipPath` string; Motion One `animate(el, { clipPath: [...] })`. GSAP's older approach used `-webkit-clip-path` for Safari — modern targets no longer need the prefix.++## See also+- [Curtain Reveal](../curtain-reveal/) — an opaque bar covers then uncovers, hiding content while masked+- [Slide Up Reveal](../slide-up-reveal/) — the same clip idea scoped to a single text line+- [Split Text Reveal](../split-text-reveal/) — per-unit reveals for type+- [Fade In / Fade Out](../fade-in-out/) — the simpler reveal this replaces when you want a shapediff --git a/animations/02-entrance-and-exit/curtain-reveal/README.md b/animations/02-entrance-and-exit/curtain-reveal/README.mdnew file mode 100644index 00000000..32367fbe--- /dev/null+++ b/animations/02-entrance-and-exit/curtain-reveal/README.md@@ -0,0 +1,55 @@+# Curtain Reveal++## What it is+A curtain reveal is a three-stage transition: an opaque bar slides across content to cover it, pauses, then slides off the far side to expose it. Unlike a clip-path reveal, the content is genuinely hidden behind the moving panel and then uncovered, so the eye registers a distinct before/after moment. It is theatrical by design and suits content that warrants the drama.++## When to use it+- Page and section transitions where a colored panel wipes across between views+- Hero intros that dramatize the first appearance of a headline or logo+- "Split" curtain effects where two halves part to reveal what is behind them+- Portfolio and editorial sites where the transition itself is part of the brand++## How it works+The curtain is an absolutely-positioned bar sitting above the content on `z-index: 2`, moved entirely with `transform: translateX/Y`. It starts off-screen, slides to `translateX(0)` to cover, then to `translateX(101%)` to leave. The three positions are driven by classes:++```css+.curtain[data-axis=h] { inset: 0 auto 0 0; width: 100%; transform: translateX(-101%); }+.curtain[data-axis=h].c-in { transform: translateX(0); } /* covers content */+.curtain[data-axis=h].c-out { transform: translateX(101%); } /* exits far side */+```++JavaScript sequences the stages with nested timers — enter, hold for `pause`, then exit — so the reveal happens *while the bar is on screen*:++```js+curtain.classList.add('c-in'); // stage A: cover+setTimeout(() => { // stage B: pause+ setTimeout(() => { // stage C: uncover+ curtain.classList.remove('c-in');+ curtain.classList.add('c-out');+ }, pause);+}, dur);+```++The `101%` (rather than `100%`) guarantees the bar clears the edge completely with no sub-pixel seam.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Curtain speed | 500ms | Time for one pass (enter or exit); the whole reveal is ~2×speed + pause |+| Pause between | 300ms | The beat the bar covers everything — this is what makes the change register |+| Direction | L→R | Horizontal (`ltr`/`rtl`) or vertical (`ttb`/`btt`) travel |+| Two curtains | off | Split mode: two halves enter from opposite sides and part |+| Curtain color | dark | The panel color — high contrast with the content heightens the drama |++## Production notes+- **Overshoot the edge with `101%`.** Ending an exit exactly at `100%` can leave a 1px sliver on fractional-DPI displays; the extra percent is the standard fix.+- **The content behind is never hidden from the DOM** — only visually covered. If the reveal gates *loading*, swap the underlying content during the `pause` stage while the bar hides the switch, so users never see the change happen.+- **Guard against re-entry.** The demo uses a `busy` flag so a second trigger can't start a new sequence mid-animation and desync the timers — important for any multi-stage, timer-driven effect.+- **Reduced motion:** the demo disables the curtain transitions under `prefers-reduced-motion`; consider revealing the content immediately instead of playing the cover/uncover theatre for those users.+- **Library equivalents:** GSAP timelines are the natural fit — `.to(curtain, { x: 0 }).to(curtain, { x: '101%' }, '+=0.3')` chains the stages with a built-in pause; Framer Motion sequences variants via `AnimatePresence`; Motion One's `animate` accepts a keyframe array with `offset` and `delay` to script the three beats.++## See also+- [Clip-Path Reveal](../clip-path-reveal/) — uncover by masking, without an opaque moving bar+- [Slide Up Reveal](../slide-up-reveal/) — a single clipped line rising into view+- [Slide In](../slide-in/) — the plain translate this dramatizes+- [Split Text Reveal](../split-text-reveal/) — staggered per-unit reveals for textdiff --git a/animations/02-entrance-and-exit/fade-in-out/README.md b/animations/02-entrance-and-exit/fade-in-out/README.mdnew file mode 100644index 00000000..e6138db0--- /dev/null+++ b/animations/02-entrance-and-exit/fade-in-out/README.md@@ -0,0 +1,50 @@+# Fade In / Fade Out++## What it is+A fade transitions an element's `opacity` between 0 and 1 — 0→1 to enter, 1→0 to exit. It is the simplest entrance animation and the cheapest to run: the compositor blends the already-painted layer, so no re-layout or re-paint is triggered. Because it carries no direction or shape, a fade reads as a neutral "appear" rather than a "move."++## When to use it+- Modal, tooltip, and popover appearance where a subtle presence change is enough+- Cross-fading between two states (loading skeleton → loaded content)+- Softening any harder motion — pair a fade with a slide or scale so the element resolves rather than snaps+- Route or view transitions where you want change without a spatial metaphor++## How it works+The card starts at `opacity: 0` and transitions to `1` when an `.in` class is added. The duration and easing are driven by CSS variables so the controls can rewrite them live:++```css+.card {+ opacity: 0;+ transition: opacity var(--dur) var(--ease);+ will-change: opacity;+}+.card.in { opacity: 1; }+```++Toggling the class is all the JS does. To replay cleanly, the demo removes `.in`, forces a reflow with `void card.offsetWidth`, then re-adds it — without that reflow the browser coalesces the remove/add into no change and the transition never fires:++```js+card.classList.remove('in');+void card.offsetWidth; // flush styles so the next add restarts the transition+card.classList.add('in');+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Duration | 600ms | Under 150ms barely registers; over 1s feels sluggish for UI |+| Easing | `ease-out` | Fast start, gentle settle — the natural feel for an entrance |+| Hold time | 800ms | How long the element stays visible before the auto-loop fades it out |+| Auto-loop | off | Cycles in → hold → out for demonstration |++## Production notes+- **Animate `opacity`, nothing else.** It is compositor-only, so a fade holds 60fps even on low-end mobile. Fading `visibility` or `display` instead does not animate at all — those are discrete properties.+- **`display: none` can't be transitioned.** If an element must leave the layout after fading, listen for `transitionend` (or use `transition-behavior: allow-discrete` with `@starting-style`) before removing it, otherwise it vanishes before the fade completes.+- **Reduced motion:** the demo shortens the fade to a 300ms linear cross-dissolve under `prefers-reduced-motion` rather than killing it — a fade is already gentle, so a faster version stays comfortable.+- **Library equivalents:** GSAP `gsap.to(el, { opacity: 1 })` or the `.fromTo()` form; Framer Motion `animate={{ opacity: 1 }}` with `AnimatePresence` for exit fades; Motion One `animate(el, { opacity: [0, 1] })`.++## See also+- [Slide In](../slide-in/) — add directional travel to the fade+- [Scale In / Zoom In](../scale-in/) — pair a fade with a scale for a physical arrival+- [Blur In](../blur-in/) — fade combined with a focus pull+- [Clip-Path Reveal](../clip-path-reveal/) — reveal without changing opacity at alldiff --git a/animations/02-entrance-and-exit/flip-in/README.md b/animations/02-entrance-and-exit/flip-in/README.mdnew file mode 100644index 00000000..273dc427--- /dev/null+++ b/animations/02-entrance-and-exit/flip-in/README.md@@ -0,0 +1,56 @@+# Flip In++## What it is+Flip In rotates an element from an edge-on flat plane into full view, using CSS 3D transforms to make the card appear to swing toward the viewer like a hinged panel. The defining detail is that `perspective` lives on the *parent* container, not the rotating card — without it, a `rotateY` collapses into a flat horizontal squash with no sense of depth.++## When to use it+- Card entrances in dashboards, galleries, and onboarding flows+- Revealing the "front" of something that conceptually has two sides (flashcards, tiles)+- Modals or panels that should feel like they physically arrive rather than fade in+- Anywhere a small dose of dimensionality distinguishes one element from a flat layout++## How it works+The stage sets `perspective`, establishing a shared vanishing point for its children. The card starts rotated (90° by default) and transitions to 0° on `.in`. Because perspective is inherited from the parent's 3D context, the rotation renders as a true swing:++```css+.stage{perspective:var(--persp)}+.card{+ opacity:0;+ transform:rotateY(var(--rot-y)) rotateX(var(--rot-x));+ transform-origin:var(--origin);+ transition:transform var(--dur) var(--ease),opacity var(--dur) var(--ease)}+.card.in{opacity:1;transform:rotateY(0deg) rotateX(0deg)}+```++The axis controls decide which rotation carries the starting angle — Y for a horizontal hinge, X for a vertical one, or both for a corner flip:++```js+const ry=axis==='X'?'0deg':rot+'deg';+const rx=axis==='Y'?'0deg':rot+'deg';+document.documentElement.style.setProperty('--rot-y',ry);+document.documentElement.style.setProperty('--rot-x',rx);+```++`transform-origin` moves the hinge to an edge (top, bottom, left) so the card swings from that side rather than pivoting around its center.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Perspective (`--persp`, on parent) | 1000px | Viewer distance; lower = more dramatic foreshortening, higher = subtle |+| Starting rotation (`--rot-y` / `--rot-x`) | 90° | The flat-plane angle to open from; 90° starts fully edge-on |+| Flip axis | Y (horizontal) | Which axis carries the rotation — Y hinge, X hinge, or both |+| Transform origin | center | Where the hinge sits; an edge origin swings the card from that side |+| Duration (`--dur`) | 600ms | Springy easing here adds a satisfying settle at the end |++## Production notes+- **Perspective belongs on the parent**: this is the single most common mistake. Setting `perspective` on the card itself (via `transform: perspective(...)`) applies per-element and won't share a vanishing point across siblings; the container `perspective` property is what creates a coherent 3D scene.+- **Backface at steep angles**: past ~90° you see the element's back. Add `backface-visibility:hidden` if the reverse side shouldn't show, or a second face for a true two-sided flip.+- **`will-change:transform`**: promotes the card to its own layer so the 3D transform stays smooth; the demo sets it up front.+- **Reduced motion**: the demo replaces the flip with a plain 300ms opacity fade and no transform when `prefers-reduced-motion` is requested — 3D rotation is a strong vestibular trigger.+- **Framer Motion**: animate `rotateY` on a `motion.div` and set `style={{ transformPerspective: 1000 }}` or a `perspective` on the parent.+- **GSAP**: set `transformPerspective` (or `perspective` on the container) and tween `rotationY`; GSAP's 3D handling is built in.++## See also+- [Scale In](../scale-in/) — a flatter, 2D entrance for the same card slot+- [Rotate In](../rotate-in/) — 2D spin rather than a 3D hinge+- [Blur In](../blur-in/) — a non-spatial focal entrance alternativediff --git a/animations/02-entrance-and-exit/letter-by-letter-stagger/README.md b/animations/02-entrance-and-exit/letter-by-letter-stagger/README.mdnew file mode 100644index 00000000..47b7f19f--- /dev/null+++ b/animations/02-entrance-and-exit/letter-by-letter-stagger/README.md@@ -0,0 +1,55 @@+# Letter-by-Letter Stagger++## What it is+A letter-by-letter stagger splits a string into individual characters and animates each one on a slightly later schedule, so the phrase assembles as a cascade rather than appearing all at once. The demo offers two implementations of the same idea: a CSS *cascade* driven by per-letter `transition-delay`, and a JS *typewriter* that reveals characters one at a time behind a blinking cursor.++## When to use it+- Hero headlines and landing-page titles where the text is the focal point+- Short phrases under ~30 characters — the effect is dramatic and gets tedious on long copy+- Loading or "assembling" states that want to feel deliberate+- Typewriter mode specifically for terminal UIs, chat interfaces, and code demos++## How it works+Each character is wrapped in its own `<span class="char">` and given a custom property `--i` equal to its index. The CSS multiplies that index by a `--stagger` value to compute a per-letter `transition-delay`, so letter *n* starts `n × stagger` milliseconds after the animation is triggered:++```js+[...text].forEach((c,i)=>{+ const s=document.createElement('span');+ s.className='char';s.style.setProperty('--i',i);+ s.textContent=c===' '?' ':c;+ target.appendChild(s);+});+```++```css+[data-mode="cascade"] .char{+ opacity:0;+ transition:opacity var(--dur) var(--ease) calc(var(--i)*var(--stagger)),+ transform var(--dur) var(--ease) calc(var(--i)*var(--stagger));+}+[data-mode="cascade"][data-anim="fade-up"] .char{transform:translateY(0.4em)}+[data-mode="cascade"].done .char{opacity:1;transform:none}+```++Adding the `.done` class flips every letter to its resting state simultaneously; the staggered `transition-delay` is what spreads the visible motion out over time. The typewriter mode skips transitions entirely and instead uses a chain of `setTimeout` calls to toggle a `.visible` class on each character in sequence.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Per-letter delay (`--stagger`) | 35ms | Gap between successive letters; higher = slower, more theatrical cascade |+| Duration per letter (`--dur`) | 400ms | How long each individual letter takes to settle |+| Per-letter animation | Fade up | The transform each letter animates from: fade, scale, or `rotateY` |+| Total time | `n × stagger + dur` | Full runtime grows linearly with character count |++## Production notes+- **Accessibility**: split text still reads as separate spans to most screen readers, but wrapping the whole phrase in an `aria-label` on the container and hiding the spans with `aria-hidden` guarantees the label is announced as one string. The demo honors `prefers-reduced-motion` by forcing all letters visible with no transition.+- **Layout cost**: `display:inline-block` on each span is required for `transform` to apply, but it disables normal line-breaking within words. For wrapping headlines, split on words first, then letters inside each word.+- **Don't overuse**: per-letter is the most granular split and the most quickly grating. Reserve it for one headline per page.+- **GSAP**: `SplitText` plus a `stagger` value on a timeline is the canonical implementation and handles the wrapping-span bookkeeping for you.+- **Framer Motion**: use a parent `variants` object with `staggerChildren`, mapping each letter to a child `motion.span`.+- **Motion One**: pass an array of elements to `animate()` with a `delay: stagger(0.035)` helper.++## See also+- [Word-by-Word Reveal](../word-by-word-reveal/) — the same stagger at word granularity, better for longer text+- [Split-Text Reveal](../split-text-reveal/) — related text-splitting entrance patterns+- [Blur In](../blur-in/) — a per-letter blur makes an effective cascade transformdiff --git a/animations/02-entrance-and-exit/rotate-in/README.md b/animations/02-entrance-and-exit/rotate-in/README.mdnew file mode 100644index 00000000..e1457e60--- /dev/null+++ b/animations/02-entrance-and-exit/rotate-in/README.md@@ -0,0 +1,56 @@+# Rotate In++## What it is+Rotate In spins an element around its center as it enters, usually combined with a scale-up so it reads as *arriving* rather than merely turning in place. Because the rotation is most legible when the shape looks coherent at every angle, the technique is best suited to radially symmetric marks — icons, stars, gears, badges — and poorly suited to text or wide rectangles.++## When to use it+- Icon and badge reveals — achievement unlocks, status indicators, loading-to-done transitions+- Logos or emblems where a spin reinforces a "coming together" moment+- Small decorative elements that can absorb an energetic entrance+- Anywhere the resting shape is symmetric enough that a mid-spin frame still looks intentional++## How it works+The element starts rotated and scaled down, then transitions both back to their resting values on `.in`. A springy easing gives the spin a slight overshoot so it feels like it lands:++```css+.icon{+ opacity:0;+ transform:rotate(var(--rot-start)) scale(var(--scale-start));+ transition:transform var(--dur) var(--ease),+ opacity var(--opacity-dur,var(--dur)) var(--ease)}+.icon.in{opacity:1;transform:rotate(0deg) scale(1)}+```++The starting angle combines a base rotation with any extra full turns, and the direction flips the sign so the spin runs clockwise or counter-clockwise:++```js+const base=+rotSl.value;+const extra=extraRot*(dir==='ccw'?-360:360);+const total=base+extra;+document.documentElement.style.setProperty('--rot-start',total+'deg');+document.documentElement.style.setProperty('--scale-start',scaleTog.checked?'0':'1');+```++Extra `±360°` turns don't change the resting frame — the element always lands at `rotate(0deg)` — but they add complete revolutions to the journey, turning a subtle tilt into a full spin.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Starting rotation (`--rot-start`) | -180° | The angle the element opens from; larger = more spin |+| Extra full rotations | 0× | Adds complete `±360°` turns without altering the landing frame |+| Direction | CCW | Sign of the rotation — clockwise or counter-clockwise |+| Easing (`--ease`) | Springy `cubic-bezier(.34,1.56,.64,1)` | Overshoot makes the spin land rather than glide to a stop |+| Combine with scale | on | Scaling from 0 turns a spin-in-place into an arrival |++## Production notes+- **Symmetry matters**: rotating text or a rectangle looks like it fell over, not like it entered. The demo deliberately uses a symmetric icon so every intermediate frame reads correctly.+- **Scale sells the arrival**: rotation alone spins the element where it already is; adding `scale(0) → scale(1)` makes it feel like it travels in from nothing. The two combined are what create the "landing" quality.+- **Decouple opacity timing**: the demo lets fade run on its own duration (`--opacity-dur`) so you can, for example, fade in quickly while the spin continues — a fully-transparent spin start can otherwise look like a glitch.+- **Reduced motion**: the icon drops to a plain 300ms opacity fade with no rotation or scale when `prefers-reduced-motion` is set.+- **Framer Motion**: animate `rotate` and `scale` together in a variant, with a spring transition for the landing overshoot.+- **GSAP**: tween `rotation` and `scale` with a `back.out` ease; `back` provides the overshoot in one keyword.++## See also+- [Flip In](../flip-in/) — 3D hinge rotation rather than a flat 2D spin+- [Scale In](../scale-in/) — the scale channel this effect leans on, on its own+- [Bounce In](../bounce-in/) — another springy, personality-forward entrancediff --git a/animations/02-entrance-and-exit/scale-in/README.md b/animations/02-entrance-and-exit/scale-in/README.mdnew file mode 100644index 00000000..e9b7ded8--- /dev/null+++ b/animations/02-entrance-and-exit/scale-in/README.md@@ -0,0 +1,49 @@+# Scale In / Zoom In++## What it is+A scale-in grows an element from a small start value up to its full `scale(1)`, usually with a fade layered on top. The `transform-origin` decides which point stays anchored while the rest expands, so the element appears to pop from a corner, an edge, or its own center. With springy easing the slight overshoot makes the arrival feel physical, as if the element lands into place.++## When to use it+- Modals, dialogs, and popovers zooming up from the control that opened them+- Cards or tiles appearing in a grid, each popping into place+- Icon or badge confirmations (a checkmark scaling in after an action)+- Menus and dropdowns expanding from the button that triggered them (origin set to that corner)++## How it works+The card starts at `scale(var(--ss))` with `opacity: 0` and transitions both to their end values when `.in` is added. The start scale, origin, easing, and fade are all CSS variables the controls rewrite:++```css+.card {+ opacity: var(--fade-opacity, 0);+ transform: scale(var(--ss));+ transform-origin: var(--origin);+ transition: transform var(--dur) var(--ease),+ opacity var(--dur) var(--ease);+ will-change: transform, opacity;+}+.card.in { opacity: 1; transform: scale(1); }+```++The default easing is `cubic-bezier(.34,1.56,.64,1)` — its control point above 1 pushes the scale past 1.0 mid-transition before settling, which is the overshoot that reads as a "pop." Changing `--origin` (e.g. to `top left`) re-anchors where that pop expands from.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Start scale | 0.80 | Closer to 1 is subtle; below 0.5 reads as a big zoom |+| Duration | 500ms | Springy easing needs room to overshoot and settle — under 300ms clips the bounce |+| Easing | Springy `cubic-bezier(.34,1.56,.64,1)` | The overshoot; `ease-out` gives a calmer, flat arrival |+| Transform origin | center | The anchor point the scale grows from |+| Combine with fade | on | Prevents the element flashing at full opacity while still tiny |++## Production notes+- **Anchor the origin to the trigger.** A popover that scales from `center` feels disconnected; setting `transform-origin` to the corner nearest its button makes it feel like it grew *out of* that button.+- **Don't start from `scale(0)` with springy easing** unless you want a hard pop — the overshoot from zero is dramatic and can feel cartoonish for UI. Starting around 0.8–0.9 keeps it refined.+- **Watch text rendering during the scale.** Scaling type up from very small can look soft mid-transition; keeping the start scale high (≥0.8) and the duration short minimizes the blur.+- **Reduced motion:** the demo disables the transform under `prefers-reduced-motion` and keeps a plain fade, so the element appears without zooming.+- **Library equivalents:** GSAP `gsap.from(el, { scale: 0.8, autoAlpha: 0, ease: 'back.out(1.7)' })` — `back.out` is the same overshoot; Framer Motion `initial={{ scale: 0.8, opacity: 0 }}` with a `type: 'spring'` transition; Motion One `animate(el, { transform: ['scale(0.8)', 'none'], opacity: [0, 1] })`.++## See also+- [Fade In / Fade Out](../fade-in-out/) — the fade this layers on top of+- [Bounce In](../bounce-in/) — a more pronounced elastic entrance+- [Slide In](../slide-in/) — arrival via position instead of size+- [Flip In](../flip-in/) — arrival via 3D rotationdiff --git a/animations/02-entrance-and-exit/slide-in/README.md b/animations/02-entrance-and-exit/slide-in/README.mdnew file mode 100644index 00000000..0aa677c0--- /dev/null+++ b/animations/02-entrance-and-exit/slide-in/README.md@@ -0,0 +1,56 @@+# Slide In++## What it is+A slide-in translates an element from an off-screen (or off-position) edge into its final resting place using `transform: translate`. The motion has a direction — top, bottom, left, or right — which reads as the element *arriving* from somewhere. Paired with a simultaneous fade, it feels like natural entry; on its own it can feel mechanical.++## When to use it+- Panels, drawers, and sheets that enter from a screen edge+- Toast and notification banners sliding in from a corner+- Staggered list or card entrances where each item slides up a short distance+- Any content where the direction of arrival carries meaning (a nav sliding down from the top)++## How it works+The card holds an offset transform and, optionally, `opacity: 0`. Both the offset and the fade are stored in CSS variables that the direction and distance controls rewrite. Adding `.in` snaps the transform back to `translate(0,0)` and opacity to 1, and the `transition` animates the change:++```css+.card {+ opacity: var(--fade);+ transform: translate(var(--tx), var(--ty));+ transition: transform var(--dur) var(--ease),+ opacity var(--dur) var(--ease);+ will-change: transform, opacity;+}+.card.in { opacity: 1 !important; transform: translate(0, 0) !important; }+```++JavaScript only computes the start offset from the chosen direction and distance:++```js+const tx = dir === 'left' ? -dist : dir === 'right' ? dist : 0;+const ty = dir === 'top' ? -dist : dir === 'bottom' ? dist : 0;+root.style.setProperty('--tx', tx + 'px');+root.style.setProperty('--ty', ty + 'px');+root.style.setProperty('--fade', withFade ? '0' : '1');+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Direction | top | Which edge the element travels from |+| Distance | 200px | Travel length — short (20–40px) for subtle UI, long for dramatic entrances |+| Duration | 600ms | Longer distances need longer durations to keep velocity believable |+| Easing | `ease-out` | Decelerate into place; `cubic-bezier(.34,1.56,.64,1)` adds an overshoot |+| Combine with fade | on | Slide alone reads mechanical; the fade makes it read as arrival |++## Production notes+- **Use `transform`, never `top`/`left`/`margin`.** Translating stays on the compositor; animating layout properties forces reflow every frame and drops frames on mobile.+- **Clip the container** with `overflow: hidden` when an element slides in from off-screen, or the pre-animation offset can create a horizontal scrollbar or spill outside the intended bounds.+- **Keep travel short for real UIs.** Marketing hero entrances can travel 100–200px, but interface elements feel snappier sliding only 8–24px — enough to imply direction without a long journey.+- **Reduced motion:** the demo drops the translate under `prefers-reduced-motion` and keeps only a short opacity fade, so the content still appears but does not fly across the screen.+- **Library equivalents:** GSAP `gsap.from(el, { x: 200, autoAlpha: 0 })`; Framer Motion `initial={{ x: 200, opacity: 0 }} animate={{ x: 0, opacity: 1 }}`; Motion One `animate(el, { transform: ['translateX(200px)', 'none'], opacity: [0, 1] })`.++## See also+- [Fade In / Fade Out](../fade-in-out/) — the fade this pairs with+- [Slide Up Reveal](../slide-up-reveal/) — slide constrained behind a clip boundary+- [Scale In / Zoom In](../scale-in/) — arrival via size instead of position+- [Bounce In](../bounce-in/) — slide with an elastic settlediff --git a/animations/02-entrance-and-exit/slide-up-reveal/README.md b/animations/02-entrance-and-exit/slide-up-reveal/README.mdnew file mode 100644index 00000000..1b82d2c7--- /dev/null+++ b/animations/02-entrance-and-exit/slide-up-reveal/README.md@@ -0,0 +1,50 @@+# Slide Up Reveal++## What it is+A slide-up reveal makes a line of text rise into view from behind a fixed clipping boundary, as if emerging from underneath a solid edge. The text moves, but a masked container hides everything below the baseline, so only the arrival is visible. It is the signature typographic entrance for headlines and hero copy.++## When to use it+- Hero and headline copy on landing pages and case studies+- Line-by-line reveals where each line rises with a small stagger+- Section titles that animate in as they scroll into view+- Any place a plain fade feels too flat and you want the text to feel *lifted* into place++## How it works+There are two ways to achieve the identical visual, and the demo toggles between them. **Method A** wraps each line in an `overflow: hidden` container and pushes the inner text down by `translateY(110%)`; adding `.in` returns it to `0`. **Method B** leaves the text in place and animates a `clip-path: inset()` from fully clipped at the bottom to fully open — no wrapper needed:++```css+/* Method A — translateY inside a clipping wrapper */+.line-wrap { overflow: hidden; }+[data-method="translatey"] .line { transform: translateY(110%); }+[data-method="translatey"] .line.in { transform: translateY(0); }++/* Method B — clip-path, no wrapper required */+[data-method="clippath"] .line { clip-path: inset(100% 0 0 0); }+[data-method="clippath"] .line.in { clip-path: inset(0% 0 0 0); }+```++Multiple lines stagger through a per-line `--d` index multiplied by a `--stagger` variable in `transition-delay`:++```css+.line { transition-delay: calc(var(--d, 0) * var(--stagger)); }+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Technique | translateY | `translateY(110%)` vs `clip-path: inset(100% 0 0 0)` — same look |+| Duration | 700ms | The rise time per line |+| Easing | `cubic-bezier(.2,.7,.3,1)` | A smooth decel; springy adds a slight settle |+| Line stagger | 60ms | Delay between successive lines — 40–80ms reads as a cascade |++## Production notes+- **`translateY(110%)`, not `100%`.** The extra 10% covers descenders (g, y, p) and line-height slack so no sliver of the glyph peeks above the boundary before it moves.+- **Pick the method by tradeoff.** `translateY` inside a wrapper composites slightly cheaper and animates more smoothly, but needs the extra `.line-wrap` element. `clip-path` needs no wrapper and keeps the text as a single selectable block, at a marginally higher paint cost — the demo notes both look identical to users.+- **Reduced motion:** the demo strips the transform and clip entirely under `prefers-reduced-motion`, falling back to a plain opacity fade so nothing slides.+- **Library equivalents:** GSAP's SplitText plugin plus a `y: '110%'` tween is the classic production recipe; Framer Motion animates `y` inside a `overflow-hidden` wrapper with `staggerChildren`; Motion One `animate` with a `delay` derived from index.++## See also+- [Split Text Reveal](../split-text-reveal/) — apply this per character or word, not per line+- [Curtain Reveal](../curtain-reveal/) — a moving bar uncovers content instead of a fixed edge+- [Clip-Path Reveal](../clip-path-reveal/) — the same clip mechanic on any element+- [Slide In](../slide-in/) — unclipped directional entrydiff --git a/animations/02-entrance-and-exit/split-text-reveal/README.md b/animations/02-entrance-and-exit/split-text-reveal/README.mdnew file mode 100644index 00000000..e8112a96--- /dev/null+++ b/animations/02-entrance-and-exit/split-text-reveal/README.md@@ -0,0 +1,61 @@+# Split Text Reveal++## What it is+A split text reveal breaks a string into individual pieces — characters, words, or lines — wraps each in its own element, and animates them one after another with a staggered delay. The stagger is what turns a flat fade into a cascade that flows across the text. It is the foundation of most "kinetic typography" entrances.++## When to use it+- Headline and hero entrances where letters or words ripple into place+- Word-by-word reveals timed to feel like the phrase is being spoken+- Line-by-line reveals for longer copy blocks+- Any type entrance where a single fade feels too uniform and you want directional flow++## How it works+JavaScript splits the text and gives each unit an `--i` index custom property. CSS then multiplies that index by a `--stagger` variable inside `transition-delay`, so unit 0 starts immediately, unit 1 a beat later, and so on — no per-element timers:++```css+.unit {+ display: inline-block;+ opacity: 0;+ transition: opacity var(--dur) var(--ease) calc(var(--i) * var(--stagger)),+ transform var(--dur) var(--ease) calc(var(--i) * var(--stagger));+}+[data-anim="fade-up"] .unit { transform: translateY(0.5em); }+.splitting.in .unit { opacity: 1; transform: none; }+```++The split assigns the index as it builds the spans:++```js+[...text].forEach(c => {+ if (c === ' ') { target.appendChild(document.createTextNode(' ')); return; }+ const s = document.createElement('span');+ s.className = 'unit';+ s.style.setProperty('--i', unitIdx++); // drives its transition-delay+ s.textContent = c;+ target.appendChild(s);+});+```++Per-unit animation is swappable via `data-anim` (fade-up, fade, scale, rotate); `lines` mode additionally clips each line and slides an inner span up, combining stagger with the slide-up reveal technique.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Split mode | words | chars = finest cascade, words = readable rhythm, lines = block reveal |+| Animation per unit | fade-up | The motion each piece plays (fade, fade-up, scale, rotate) |+| Stagger delay | 30ms | Delay between units — small values ripple, large values feel deliberate |+| Duration per unit | 500ms | How long each individual piece animates |+| Easing | `cubic-bezier(.2,.7,.3,1)` | Per-unit curve; springy adds a settle on each piece |++## Production notes+- **Total time = units × stagger + duration.** Character mode on a long string multiplies fast — 40 chars × 30ms + 500ms is nearly 1.7s. Cap the stagger or switch to words/lines for longer copy so the tail does not drag.+- **Splitting breaks the text for accessibility.** A screen reader may read char-split text letter by letter, and the split destroys native word wrapping. Add `aria-label` with the full string on the container (and `aria-hidden` on the pieces), and re-run the split on resize since wrapping changes.+- **Preserve spaces deliberately.** The demo inserts real text nodes for spaces in char mode and adds trailing spaces between word spans — without that, `inline-block` units collapse the whitespace and words run together.+- **Reduced motion:** the demo collapses every per-unit transform under `prefers-reduced-motion` to a plain 300ms opacity fade, so the whole phrase appears without the cascade.+- **Library equivalents:** Splitting.js and GSAP's SplitText both do the DOM splitting for you (SplitText also handles the ARIA and re-split-on-resize); Framer Motion uses `staggerChildren` on a parent variant with child `motion.span`s; Motion One's `stagger()` helper generates the per-element delay.++## See also+- [Slide Up Reveal](../slide-up-reveal/) — the clipped line-rise this reuses in `lines` mode+- [Letter By Letter Stagger](../letter-by-letter-stagger/) — char-split cascade in depth+- [Word By Word Reveal](../word-by-word-reveal/) — word-split cascade in depth+- [Fade In / Fade Out](../fade-in-out/) — the un-staggered baselinediff --git a/animations/02-entrance-and-exit/word-by-word-reveal/README.md b/animations/02-entrance-and-exit/word-by-word-reveal/README.mdnew file mode 100644index 00000000..beed5135--- /dev/null+++ b/animations/02-entrance-and-exit/word-by-word-reveal/README.md@@ -0,0 +1,55 @@+# Word-by-Word Reveal++## What it is+A word-by-word reveal animates each word of a passage in sequence rather than all together or letter-by-letter. Words are the natural unit of reading, so a stagger of roughly 80–120ms per word tracks how the eye moves through a sentence — slow enough to feel intentional, fast enough not to make the reader wait.++## When to use it+- Multi-line body copy, quotes, and paragraph intros where per-letter would be too busy+- Sequential storytelling where you want each phrase to land before the next+- Subtitle or caption reveals timed to a voiceover+- Sectioned reveals where sentence pauses separate distinct thoughts++## How it works+The text is split on whitespace into `<span class="word">` elements, each carrying an `--i` index. The CSS derives a `transition-delay` from `--i × --stagger`, and adding the `.in` class on the container drops every word to its resting state at once — the delays fan the motion out:++```js+words.forEach((w,wi)=>{+ const s=document.createElement('span');s.className='word';+ const delay=punctTog.checked?idx*stagger+si*200:idx*stagger;+ s.style.setProperty('--i',delay/stagger);+ s.textContent=w;target.appendChild(s);+ if(wi<words.length-1)target.appendChild(document.createTextNode(' '));+ idx++;+});+```++```css+.word{display:inline-block;margin-right:0.28em;opacity:0;+ transition:opacity var(--dur) var(--ease) calc(var(--i)*var(--stagger)),+ transform var(--dur) var(--ease) calc(var(--i)*var(--stagger))}+[data-anim="fade-up"] .word{transform:translateY(0.4em)}+.splitting.in .word{opacity:1;transform:none;filter:none}+```++The "sentence pauses" option adds `si × 200ms` to the delay for each sentence, inserting a beat between lines. Because the index is stored as `delay/stagger`, the CSS math stays a single `calc()` regardless of whether pauses are on.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Per-word delay (`--stagger`) | 80ms | The reading-speed knob; below ~40ms the stagger blurs into one reveal |+| Duration per word (`--dur`) | 450ms | Settle time for each individual word |+| Easing (`--ease`) | Smooth `cubic-bezier(.2,.7,.3,1)` | Springy overshoot adds bounce; linear feels mechanical |+| Sentence pause | off (+200ms) | Extra delay injected between sentences for paragraph reveals |++## Production notes+- **Whitespace preservation**: keeping a real text node (a literal space) between word spans lets the browser wrap and justify normally, which pure `margin-right` spacing cannot do reliably across fonts.+- **Runtime scales with length**: total time is `wordCount × stagger + dur`. A long paragraph at 120ms/word can run for many seconds — cap the word count or the stagger for anything past a sentence or two.+- **Reduced motion**: the demo collapses to a single 300ms linear fade with no transform when `prefers-reduced-motion` is set, so the content still appears without the sequential motion.+- **GSAP**: `SplitText({type:"words"})` plus `stagger` on a tween is the direct equivalent.+- **Framer Motion**: a container variant with `staggerChildren:0.08` and a per-word child variant reproduces this without manual index math.+- **Motion One**: `stagger(0.08)` passed as the `delay` option to `animate()`.++## See also+- [Letter-by-Letter Stagger](../letter-by-letter-stagger/) — the finer-grained sibling, for short headlines+- [Split-Text Reveal](../split-text-reveal/) — general text-splitting entrance techniques+- [Fade In / Out](../fade-in-out/) — the base opacity transition each word usesdiff --git a/animations/03-page-transitions/README.md b/animations/03-page-transitions/README.mdnew file mode 100644index 00000000..91cdeee2--- /dev/null+++ b/animations/03-page-transitions/README.md@@ -0,0 +1,18 @@+# Page Transitions++Full-page transitions between routes or views — how one screen gives way to the next. Crossfades, slides, portals, morphs, and the browser-native View Transitions API.++## Entries++- [View Transitions API](view-transitions-api/) — `document.startViewTransition()` captures before/after and animates the swap automatically.+- [Shared Element Transition](shared-element-transition/) — a thumbnail morphs continuously into a detail hero as the page changes; the FLIP technique applied.+- [Morph Transition](morph-transition/) — an SVG path morphs between page-specific shapes via point-by-point interpolation.+- [Crossfade](crossfade/) — both pages visible simultaneously at ~50% opacity mid-transition; compared with sequential fade.+- [Slide Transition](slide-transition/) — directional slides with forward/back awareness, matching native iOS and Android navigation.+- [Zoom Transition](zoom-transition/) — zoom-in, zoom-out, and pull-through scale variants, each implying different spatial depth.+- [Flash / Light Leak](flash-transition/) — a colored flash peaks at full opacity, hides the page swap, then fades to reveal the new scene.+- [Blur Transition](blur-transition/) — the current page blurs and fades out, then the new page sharpens in; a defocus wipe.+- [Elastic Transition](elastic-transition/) — spring physics overshoot before settling; CSS keyframes or a live JS spring.+- [Portal / Tunnel Zoom](portal-zoom/) — `clip-path` expands from a portal element's center, zooming the viewport into the next page.+- [Dissolve](dissolve/) — random tiles fade at staggered delays; a non-uniform wipe that reads as dissolving rather than fading.+- [FLIP Technique](flip-technique/) — First-Last-Invert-Play; layout changes animated cheaply by measuring position deltas.diff --git a/animations/03-page-transitions/blur-transition/README.md b/animations/03-page-transitions/blur-transition/README.mdnew file mode 100644index 00000000..17059e32--- /dev/null+++ b/animations/03-page-transitions/blur-transition/README.md@@ -0,0 +1,56 @@+# Blur Transition++## What it is+A blur transition defocuses the current page until it fades out, then brings the incoming page in from blurred to sharp. The effect mimics a camera pulling focus between two subjects, so the change of scene reads as a shift of attention rather than a hard cut. Blur and opacity animate together for a soft, cinematic wipe.++## When to use it+- Transitions between visually rich pages where a hard cut feels abrupt+- Photography, film, and editorial sites where a rack-focus metaphor fits the content+- Modal or detail views that should feel like the background recedes out of focus+- User-initiated navigation only — never on autoplaying carousels, where the cost adds up++## How it works+The outgoing page transitions its `filter` (and optionally `opacity`) up to a maximum blur, then the incoming page is pre-blurred, made active, and transitioned back to `blur(0px)`. Because filter transitions do not compose across an element swap, the incoming page's blur is set with `transition: none`, forced to commit over two animation frames, and only then animated to sharp.++```js+function doTransition(prev, next) {+ const o = document.getElementById('p' + prev), n = document.getElementById('p' + next);+ o.style.transition = `filter ${dur}ms ${ease}, opacity ${dur}ms ${ease}`;+ o.style.filter = `blur(${maxBlur}px)`;+ if (withFade) o.style.opacity = '0';++ const swapAfter = overlap ? Math.round(dur * 0.5) : dur;+ setTimeout(() => {+ o.classList.remove('active');+ n.style.transition = 'none';+ n.style.filter = `blur(${maxBlur}px)`; n.style.opacity = '0'; n.classList.add('active');+ requestAnimationFrame(() => requestAnimationFrame(() => {+ n.style.transition = `filter ${dur}ms ${ease}, opacity ${dur}ms ${ease}`;+ n.style.filter = 'blur(0px)'; n.style.opacity = '1'; // sharpen in+ }));+ }, swapAfter);+}+```++An "overlap" option starts the incoming sharpen at 50% of the outgoing blur instead of waiting for it to finish, cutting the total time roughly in half while the two stages cross.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Max blur | 20px | Peak defocus. Above ~30px is heavy on the GPU and can look muddy |+| Stage duration | 400ms | Time per stage (blur-out, sharpen-in). Doubles unless stages overlap |+| Easing | ease-in-out | `ease-in-out` feels like a controlled focus pull; `ease-out` snaps sharp faster |+| Blur + fade | on | Combining with opacity hides the swap; blur-only keeps both pages visible mid-transition |+| Overlap stages | off | Runs the two halves concurrently for a faster, softer cross |++## Production notes+- **GPU cost.** Large-radius `filter: blur()` over a full-viewport element is one of the more expensive things you can animate. Keep the blurred region as small as practical, cap the radius on mobile, and avoid running it during scroll.+- **The double `requestAnimationFrame`.** Setting the pre-blur with `transition: none` and then flipping to the animated transition requires two frames — one to commit the start state, one to start the tween. A single frame occasionally drops the animation and the page pops in sharp.+- **Fringing.** Blurring an element with a hard rectangular edge can reveal a faint halo where the blur samples past the bounds. A subtle `overflow: hidden` container or a slight scale keeps the edge clean.+- **Library equivalents.** The View Transitions API can animate `filter` on `::view-transition-old`/`-new` for the same effect with far less bookkeeping. Framer Motion animates `filter: 'blur(20px)'` to `'blur(0px)'` via `animate`; GSAP does the same through its CSS plugin. Barba.js `leave`/`enter` hooks host the blur-out and sharpen-in halves.++## See also+- [Crossfade](../crossfade/) — the opacity blend blur is layered on top of+- [Flash / Light Leak](../flash-transition/) — hides the swap with brightness instead of defocus+- [Dissolve](../dissolve/) — a tiled, non-uniform wipe for a different texture+- [Zoom Transition](../zoom-transition/) — scale rather than focus to shift attentiondiff --git a/animations/03-page-transitions/crossfade/README.md b/animations/03-page-transitions/crossfade/README.mdnew file mode 100644index 00000000..c524650d--- /dev/null+++ b/animations/03-page-transitions/crossfade/README.md@@ -0,0 +1,53 @@+# Crossfade Transition++## What it is+A crossfade transitions between two pages by fading the outgoing one out and the incoming one in *at the same time*, so both are partially visible around the midpoint. This overlap distinguishes a true crossfade from a sequential fade, which fades the old page fully out before the new one begins and leaves a brief blank frame. The demo runs both modes side by side and reports the live opacity of each page so the difference is measurable, not just felt.++## When to use it+- Neutral, non-directional navigation where no spatial relationship between pages is implied+- Content swaps within a persistent shell (tabs, filters, image galleries)+- The safe default transition — it works when you can't justify a slide or zoom+- Situations needing the calmest possible motion, since nothing moves, only opacity changes++## How it works+In simultaneous mode both pages get the same-duration opacity transition and flip at once; in sequential mode each gets half the duration, staged one after the other. A `requestAnimationFrame` loop samples both computed opacities live so you can watch them cross:++```js+if(mode==='true'){+ // Simultaneous: both fade together over the full duration+ oldEl.style.transition=`opacity ${dur}ms ${easeSel.value}`;+ newEl.style.transition=`opacity ${dur}ms ${easeSel.value}`;+ oldEl.style.opacity='0'; newEl.style.opacity='1';+}else{+ // Sequential: fade old out over half, then new in over half+ const half=Math.round(dur/2);+ oldEl.style.opacity='0';+ setTimeout(()=>{+ newEl.style.opacity='0'; newEl.classList.add('active');+ requestAnimationFrame(()=>requestAnimationFrame(()=>{ newEl.style.opacity='1'; }));+ }, half+50);+}+```++Both pages are absolutely positioned in the same stacking context (`inset:0`), so they overlap perfectly and only their opacity changes. In simultaneous mode the outgoing page reaches ~0.5 exactly as the incoming page does, giving the momentary blend; in sequential mode the stage passes through a fully blank frame at the handoff.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Mode | Simultaneous | Simultaneous overlaps both pages; sequential inserts a blank midpoint |+| Duration | 500ms | Full crossfade length; sequential splits this into two halves |+| Easing | ease-in-out | Opacity curve; linear reads most evenly for a pure fade |+| Overlap opacity | ~0.5 | Where the two pages meet in simultaneous mode — the defining trait |++## Production notes+- **Stack both pages absolutely** so they occupy the same box. If they reflow the document, opacity alone won't give a clean blend.+- **Simultaneous double-fade can look washed out** on light backgrounds, because two 50%-opacity layers over a bright backdrop sum brighter than either page. Sequential avoids this at the cost of a blank beat.+- **A `+50ms` guard** after each `setTimeout` in the demo ensures the transition has finished before styles are reset; without slack the cleanup can clip the tail of the fade.+- **Reduced motion** swaps the `.active` class with no opacity transition at all.+- **Library equivalents**: this is the default `::view-transition-old/new(root)` behavior of the View Transitions API. Framer Motion's `AnimatePresence` with `initial/animate/exit` opacity, GSAP timelines, and React Transition Group all express the same overlap.++## See also+- [View Transitions API](../view-transitions-api/) — crossfade is its built-in default+- [Dissolve](../dissolve/) — a textured variant of the same fade principle+- [Slide Transition](../slide-transition/) — a directional alternative when pages have a spatial order+- [Blur Transition](../blur-transition/) — pairs a blur with the opacity changediff --git a/animations/03-page-transitions/dissolve/README.md b/animations/03-page-transitions/dissolve/README.mdnew file mode 100644index 00000000..215c1816--- /dev/null+++ b/animations/03-page-transitions/dissolve/README.md@@ -0,0 +1,57 @@+# Dissolve++## What it is+A dissolve is a non-uniform fade: the screen is divided into a grid of tiles, and each tile fades at a slightly different time according to a delay pattern. Because regions disappear out of sync, the change reads as the old scene dissolving into grain rather than the whole image fading at once. The delay pattern — random, diagonal, or radial — determines the texture of the wipe.++## When to use it+- Transitions that want more texture than a plain crossfade but less drama than a slide or zoom+- Photo and video contexts where a film-style dissolve matches the medium+- Retro or glitch aesthetics, where a coarse tile grid evokes pixel-era screen wipes+- Directional reveals (diagonal, radial) that hint at where the eye should travel next++## How it works+A grid overlay of `n × n` empty tiles is built over the outgoing page. Each tile gets a per-tile `transition-delay` from a pattern function, then all tiles are faded to opaque at once — the staggered delays produce the dissolve. The page swap happens partway through, hidden under the tiles, and the overlay is cleared (or optionally faded back out for a symmetric dissolve-in).++```js+function getDelays(n, style) {+ const total = n * n;+ if (style === 'random') { // shuffle tile order+ const order = Array.from({length: total}, (_, i) => i).sort(() => Math.random() - 0.5);+ return order.map((_, i) => order.indexOf(i) / total);+ }+ if (style === 'diagonal') { // (row + col) sweep+ return Array.from({length: total}, (_, i) => {+ const r = Math.floor(i / n), c = i % n;+ return (r + c) / (2 * (n - 1));+ });+ }+ // radial: distance from the grid center+ return Array.from({length: total}, (_, i) => {+ const r = Math.floor(i / n) - n / 2, c = i % n - n / 2;+ return Math.sqrt(r * r + c * c) / Math.sqrt(2) * n / 2 / (n * 0.8);+ });+}+```++Each tile's inline style bakes the normalized delay into a real transition: `transition: opacity <fadeDur>ms ease <delay>ms`. The delays are computed in pure JS and applied per element, so the browser handles all the actual animation — no per-frame loop.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Dissolve style | random | `random` = grain, `diagonal` = sweep, `radial` = wipe from center out |+| Granularity | 8×8 | Tile count. Coarse reads as blocks; fine (16×16) approaches a smooth fade |+| Duration | 800ms | Total wipe time; the swap fires at ~60% through, under the tiles |+| Dissolve in + out | off | Fades tiles back out over the new page for a symmetric transition |+| Show tile mask | off | Outlines each tile in red to expose the grid structure |++## Production notes+- **Random needs a stable order.** Shuffling the tile order once and mapping each tile to its rank keeps the pattern coherent; re-randomizing per frame would flicker. This demo shuffles a single order array and reuses it.+- **Tile count is a cost knob.** A 16×16 grid is 256 animated elements — still cheap because each only transitions `opacity`, but pushing much finer starts to cost layout and memory. Beyond ~24×24 a canvas or a noise-texture mask is a better tool.+- **Swap timing.** The page underneath is swapped while enough tiles are opaque to hide it (here at ~60% of the duration). Swap too early and the incoming page shows through gaps; too late and the reveal feels delayed.+- **Library equivalents.** The View Transitions API can dissolve with a masked `::view-transition-old` but does not offer per-tile stagger out of the box — a generated mask image is the native route. GSAP's `stagger` with a `grid` and `from: 'random'` reproduces this directly. Shader-based dissolves sample a noise texture against a rising threshold, which is the same idea at pixel granularity.++## See also+- [Crossfade](../crossfade/) — the uniform fade this breaks into staggered tiles+- [Flash / Light Leak](../flash-transition/) — another overlay that hides the swap+- [Blur Transition](../blur-transition/) — a softer non-tiled way to mask the change+- [Slide Transition](../slide-transition/) — a directional wipe without the tile texturediff --git a/animations/03-page-transitions/elastic-transition/README.md b/animations/03-page-transitions/elastic-transition/README.mdnew file mode 100644index 00000000..c9511337--- /dev/null+++ b/animations/03-page-transitions/elastic-transition/README.md@@ -0,0 +1,58 @@+# Elastic Transition++## What it is+An elastic transition overshoots its target and settles back with a spring-like wobble instead of easing smoothly to a stop. The overshoot gives the motion a sense of weight and momentum, as if the page were pulled into place by a rubber band. It can be baked into CSS keyframes for cheapness, or simulated live in JavaScript for physical accuracy.++## When to use it+- Playful, characterful interfaces where motion is part of the personality+- Panels, cards, and pages that slide in and should feel physical rather than mechanical+- Confirmation or arrival moments where a small bounce signals "landed"+- Cases where a gesture may be interrupted — a live spring reacts to interruption, a keyframe cannot++## How it works+This demo offers two modes. The CSS mode writes a `@keyframes` rule at runtime whose intermediate percentages push past the endpoint before returning, with the overshoot amount scaled by a control. The JS mode integrates an actual spring each frame: force equals `-stiffness × displacement − damping × velocity`, and the loop runs until both position and velocity fall below a threshold.++```js+function doSpring(prev, next) {+ let pos = -100, vel = 0, target = 0; // start off-screen right+ let lastTime = null;+ function tick(now) {+ if (!lastTime) lastTime = now;+ const dt = Math.min((now - lastTime) / 1000, 0.05);+ lastTime = now;+ const f = -stiffness * (pos - target) - damping * vel; // Hooke's law + damping+ vel += f * dt;+ pos += vel * dt;+ n.style.transform = `translateX(${pos.toFixed(2)}%)`;+ if (Math.abs(pos - target) < 0.5 && Math.abs(vel) < 0.5) {+ n.style.transform = ''; // settled — clean up+ } else {+ requestAnimationFrame(tick);+ }+ }+ requestAnimationFrame(tick);+}+```++The `dt` is clamped to 50ms so a dropped frame or a backgrounded tab cannot inject a huge time step that would make the spring explode. Recorded positions are plotted to a small canvas so the overshoot-and-settle curve is visible.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Mode | CSS keyframes | Keyframes are pre-baked and cheap; JS spring is physical and interruptible |+| Overshoot intensity (CSS) | 60% | How far past the endpoint the keyframes push before settling |+| Duration (CSS) | 900ms | Total keyframe length; longer lets more oscillations read |+| Stiffness (JS) | 180 | Spring constant. Higher snaps to target faster with more overshoot |+| Damping (JS) | 20 | Resistance. Low damping oscillates for longer; high damping settles flat |++## Production notes+- **Stiffness and damping interact.** Below critical damping (`damping < 2√stiffness`) the spring oscillates; at or above it, it eases in without bounce. Tune the pair together — raising stiffness usually needs more damping to stay tasteful.+- **Clamp the time step.** Integrating with the raw frame delta is the classic spring bug: one long frame and `pos` shoots to infinity. The `Math.min(dt, 0.05)` clamp is not optional.+- **CSS keyframe overshoot can clip.** If a page translates fully to its edge before the bounce completes, the overshoot slides content out of the visible bounds. Reserve a little slack or let the container overflow during the animation.+- **Library equivalents.** Framer Motion and React Spring take `stiffness`/`damping` directly and handle interruption for you — reach for them rather than hand-rolling the integrator in production. GSAP's `elastic.out` easing approximates the CSS-keyframe feel. CSS `linear()` easing can now encode a sampled spring curve without JavaScript at all.++## See also+- [Slide Transition](../slide-transition/) — the linear slide this adds spring physics to+- [Zoom Transition](../zoom-transition/) — another transform that benefits from overshoot+- [FLIP Technique](../flip-technique/) — pairs a springy easing with measured layout deltas+- [Morph Transition](../morph-transition/) — shape change that also reads as physicaldiff --git a/animations/03-page-transitions/flash-transition/README.md b/animations/03-page-transitions/flash-transition/README.mdnew file mode 100644index 00000000..45f1de4a--- /dev/null+++ b/animations/03-page-transitions/flash-transition/README.md@@ -0,0 +1,52 @@+# Flash / Light Leak++## What it is+A flash transition covers the screen with a colored overlay that peaks at full opacity, swaps the page content while it is hidden, then fades the overlay away to reveal the new scene. The eye reads the overexposure as a single continuous moment, so the underlying content swap is never seen. Cinema uses the same trick to hide edits inside a burst of light.++## When to use it+- Masking a cheap or instant content swap where a crossfade would look flat+- High-energy brand sites, product launches, and portfolio galleries that want punch+- Music, fashion, and event pages where a light leak matches the visual language+- Any navigation where you want the transition itself to read as a deliberate beat, not just plumbing++## How it works+A single absolutely-positioned overlay sits above the pages at a high `z-index`. The transition runs in three phases driven by two `setTimeout` calls: fade the overlay up over `flashIn`, swap the active page at peak opacity, then fade the overlay back down over `flashOut`. The content change happens while the overlay is opaque, so it is invisible.++```js+function doTransition(prev, next) {+ flashEl.style.transition = `opacity ${flashIn}ms ease-in, filter ${flashIn}ms ease`;+ flashEl.style.opacity = intensity; // fade the flash up+ setTimeout(() => {+ // Peak — swap the page behind the opaque flash+ document.getElementById('p' + prev).classList.remove('active');+ document.getElementById('p' + next).classList.add('active');+ requestAnimationFrame(() => {+ flashEl.style.transition = `opacity ${flashOut}ms ease-out, filter ${flashOut}ms ease`;+ flashEl.style.opacity = '0'; // fade the flash down to reveal+ });+ }, flashIn);+}+```++The swap is deferred to a `requestAnimationFrame` after the class change so the browser commits the new transition before starting the fade-out. An optional `blur()` filter applied during the flash softens the edge and sells the light-leak feel.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Flash-in duration | 200ms | Ramp to peak. Faster feels like a camera strobe; slower feels like a wash |+| Flash-out duration | 320ms | Reveal ramp. Usually longer than the in, so the new page eases into view |+| Intensity (peak opacity) | 1.00 | Below 1.0 lets the swap show through faintly — keep at 1.0 to fully hide it |+| Flash color | white | White reads as overexposure; tinted (gold, cyan) reads as a stylized light leak |+| Blur during flash | off | Adds a soft bloom to the peak, disguising the hard overlay edge |++## Production notes+- **Swap only at true peak.** If intensity drops below ~0.9 the content change becomes visible as a hard cut through the overlay. Keep peak opacity high, and only lower it deliberately for a see-through effect.+- **Guard against re-entry.** An `animating` flag blocks new navigations mid-transition; without it a fast double-click can swap pages while the overlay is already fading and expose the seam.+- **Accessibility.** A full-screen white flash can be uncomfortable or trigger photosensitivity. This demo hides the overlay entirely under `prefers-reduced-motion: reduce` and swaps instantly instead — do the same in production, and avoid rapid repeated flashes.+- **Library equivalents.** The View Transitions API can reproduce this by animating a `::view-transition-group` with a flash-colored pseudo-element, though a dedicated overlay is simpler. GSAP timelines chain the fade-in, swap callback, and fade-out cleanly. Barba.js exposes `leave`/`enter` hooks that map directly onto the peak-and-reveal structure.++## See also+- [Crossfade](../crossfade/) — the plain opacity blend this technique dresses up+- [Dissolve](../dissolve/) — another overlay-masked swap, tiled instead of solid+- [Blur Transition](../blur-transition/) — defocus rather than overexposure to hide the change+- [Portal / Tunnel Zoom](../portal-zoom/) — a clip-path reveal that also masks the swapdiff --git a/animations/03-page-transitions/flip-technique/README.md b/animations/03-page-transitions/flip-technique/README.mdnew file mode 100644index 00000000..780c821e--- /dev/null+++ b/animations/03-page-transitions/flip-technique/README.md@@ -0,0 +1,62 @@+# FLIP Technique++## What it is+FLIP — First, Last, Invert, Play — is a method for animating layout changes that CSS cannot transition directly, such as reordering a grid or switching column counts. Instead of animating the expensive layout properties, it lets the browser jump elements to their final positions instantly, then uses a cheap `transform` to make them *appear* to still be in their old spots, and animates that transform away. The result looks like the elements glided to their new layout, but only `transform` ever animated.++## When to use it+- Reordering, sorting, filtering, or shuffling a list or grid+- Switching layouts (3 columns → list) where items change both position and size+- Adding or removing items and having the neighbors slide to accommodate+- Any "the layout changed and I want it to animate" case that `transition` alone can't handle++## How it works+The four steps map onto four blocks of code. **First:** record every card's bounding rect. **Last:** apply the new layout so cards snap to their final positions. **Invert:** for each card, compute the delta between its old and new position and apply a `transform` that visually returns it to the start. **Play:** on the next frames, transition that transform to zero so the card glides to where it really is.++```js+// FIRST — record positions before the change+const first = {};+cards.forEach(c => { first[c.id] = c.getBoundingClientRect(); });++// LAST — apply the new layout (cards jump instantly)+renderCards();+grid.offsetHeight; // force reflow++// INVERT — transform each card back to its original spot+newCards.forEach(c => {+ const f = first[c.id], last = c.getBoundingClientRect();+ const dx = f.left - last.left, dy = f.top - last.top;+ c.style.transform = `translate(${dx.toFixed(1)}px, ${dy.toFixed(1)}px)`;+ c.style.transition = 'none';+});++// PLAY — animate the transform to zero+requestAnimationFrame(() => requestAnimationFrame(() => {+ newCards.forEach(c => {+ c.style.transition = `transform ${dur}ms ${ease}`;+ c.style.transform = '';+ });+}));+```++Cards are matched across the re-render by a stable `id`, so a card that moves from one grid slot to another is tracked correctly. The double `requestAnimationFrame` guarantees the inverted (start) state is committed before the transition to zero begins.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Duration | 500ms | Glide time from inverted position to final. 300–600ms reads as deliberate |+| Easing | Smooth `cubic-bezier(.2,.7,.3,1)` | Controls the settle; a springy curve adds overshoot |+| Matching key | element `id` | How First positions are paired to Last elements; must be stable across re-render |+| Show Invert step | off | Badges each card during the invert phase to expose the hidden mechanism |++## Production notes+- **Only `transform` animates.** That is the whole point — `transform` and `opacity` are compositor-friendly and skip layout and paint, so FLIP animates dozens of reflowing elements at 60fps where transitioning `width`/`top` would jank.+- **Read then write, once.** Batch all `getBoundingClientRect` reads (First) before any style writes (Last/Invert) to avoid layout thrashing. Reading and writing in an interleaved loop forces repeated synchronous layouts.+- **Size changes need scale.** This demo animates position via `translate`; when cards also change dimensions (list mode), add `scaleX`/`scaleY` from the old size to the new, or the resize will pop rather than glide.+- **`will-change: transform`** on the animated cards hints the compositor to promote them to their own layer ahead of time, smoothing the first frame — used here on `.flip-card`.+- **Library equivalents.** React's `<AnimatePresence>` and Framer Motion's `layout` prop implement FLIP automatically for layout changes. GSAP's Flip plugin is a direct, batteries-included implementation. The View Transitions API achieves similar layout-change animation natively by snapshotting before and after, without manual rect math.++## See also+- [Shared Element Transition](../shared-element-transition/) — FLIP applied to a single element across pages+- [Morph Transition](../morph-transition/) — animating shape as well as position between states+- [Elastic Transition](../elastic-transition/) — pair FLIP's Play step with a springy easing+- [View Transitions API](../view-transitions-api/) — the browser-native successor to hand-rolled FLIPdiff --git a/animations/03-page-transitions/morph-transition/README.md b/animations/03-page-transitions/morph-transition/README.mdnew file mode 100644index 00000000..ae98187d--- /dev/null+++ b/animations/03-page-transitions/morph-transition/README.md@@ -0,0 +1,51 @@+# Morph Transition++## What it is+A morph transition interpolates one SVG shape into another by moving each point of the path toward its counterpart in the target shape. Instead of fading or swapping graphics, the outline flows continuously — a circle unfolds into a hexagon, a hexagon sharpens into a star. The demo ties the morph to page navigation: a logo mark reshapes as the user moves between Home, Gallery, and About.++## When to use it+- Logo or brand marks that reshape to signal section changes+- Icon state changes (play↔pause, menu↔close, checkmark reveal)+- Data-shape transitions where the geometry itself carries meaning+- Decorative continuity between pages that share a persistent element++## How it works+Morphing requires the source and target paths to have the **same number of points in the same order**. The demo normalizes every shape to 12 vertices, then on each animation frame linearly interpolates each `[x,y]` pair by an eased progress value and rebuilds the path string:++```js+function lerp(a,b,t){ return a+(b-a)*t }++function startMorph(from,to,done){+ const start=performance.now();+ function tick(now){+ const t=Math.min((now-start)/dur,1), et=easeFn(t);+ const pts=from.map(([ax,ay],i)=>[ lerp(ax,to[i][0],et), lerp(ay,to[i][1],et) ]);+ morphPath.setAttribute('d', pts2path(pts));+ if(t<1) morphRaf=requestAnimationFrame(tick); else done?.();+ }+ morphRaf=requestAnimationFrame(tick);+}+```++The shapes are generated to guarantee matching vertex counts: the circle samples 12 points around its radius, the hexagon interleaves its 6 corners with 6 edge midpoints, and the star alternates 6 outer and 6 inner points. Because index `i` of the source maps to index `i` of the target, each point has a well-defined destination and the outline never tears. A "show control points" toggle overlays the 12 vertices so the correspondence is visible.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Morph duration | 700ms | Length of the point interpolation; slower reads as more deliberate |+| Easing | ease-in-out | `easeFn` selects linear, ease-out (`1-(1-t)³`), ease-in-out, or a springy overshoot |+| Vertex count | 12 | Every shape is normalized to this; source and target must match exactly |+| Point order | clockwise from top | Mismatched ordering makes the shape twist or collapse mid-morph |++## Production notes+- **Point count and order are everything.** If two paths differ in vertex count, you must resample one to match before interpolating — mismatches produce garbage. Tools like flubber solve this by inserting and pairing points automatically.+- **Naive `lerp` cuts corners** on paths with curves. This demo uses straight `L` segments between points; morphing Bézier control points requires interpolating the control handles too.+- **`requestAnimationFrame` + `performance.now()`** drive the timing manually here rather than CSS, because CSS can't interpolate the `d` attribute's point list across arbitrary shapes.+- **Reduced motion** skips the morph and snaps the page swap, leaving the mark in its target shape.+- **Library equivalents**: GSAP's MorphSVG plugin and the standalone flubber library handle point resampling and pairing for arbitrary paths. Framer Motion animates simple SVG `path` values; Lottie bakes shape morphs exported from After Effects.++## See also+- [Shared Element Transition](../shared-element-transition/) — continuity via position rather than shape+- [Flip Technique](../flip-technique/) — another measure-and-interpolate approach+- [Crossfade](../crossfade/) — the page-content transition paired with this morph+- [Elastic Transition](../elastic-transition/) — spring-based motion related to the springy easing optiondiff --git a/animations/03-page-transitions/portal-zoom/README.md b/animations/03-page-transitions/portal-zoom/README.mdnew file mode 100644index 00000000..01facfde--- /dev/null+++ b/animations/03-page-transitions/portal-zoom/README.md@@ -0,0 +1,52 @@+# Portal / Tunnel Zoom++## What it is+A portal zoom treats a small on-screen element as a window into the next page: clicking it expands a circular (or rectangular) clip-path outward from the portal's center until the incoming page fills the whole stage. The effect reads as diving through the portal rather than swapping to a new URL. The destination is already rendered behind the mask before the animation begins, so the growth reveals it rather than loading it.++## When to use it+- Gallery or case-study entries where a thumbnail should "open into" its detail view+- Spatial navigation metaphors — rooms, worlds, chapters connected by doorways+- Landing pages with a single strong call-to-action that deserves a dramatic reveal+- Any transition where the origin point of the motion carries meaning (this card, this button)++## How it works+The incoming page is clipped to a zero-radius circle positioned at the portal's center, made active, forced to reflow, and then transitioned to a circle large enough to cover the stage. The portal's center is measured against the stage rect so the reveal always originates from exactly where the user clicked.++```js+const areaRect = area.getBoundingClientRect();+let px = '50%', py = '50%';+if (portalEl) {+ const pr = portalEl.getBoundingClientRect();+ px = ((pr.left + pr.width / 2 - areaRect.left) / areaRect.width * 100).toFixed(1) + '%';+ py = ((pr.top + pr.height / 2 - areaRect.top) / areaRect.height * 100).toFixed(1) + '%';+}+nextEl.style.clipPath = `circle(0% at ${px} ${py})`; // pinhole at the portal+nextEl.style.transition = 'none';+nextEl.classList.add('active');+nextEl.offsetHeight; // force reflow to commit start+nextEl.style.transition = `clip-path ${dur}ms ${easeSel.value}`;+nextEl.style.clipPath = `circle(150% at ${px} ${py})`; // expand to cover the stage+```++The end radius is `150%` rather than `100%` because the circle must reach the corners of the rectangle, which are farther from the center than the edges. Reading `offsetHeight` between setting the start clip and the animated transition forces the browser to commit the pinhole state so the growth animates from zero. `ease-in` accelerates outward and reads as a zoom-in; `ease-out` reads as a zoom-out.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Portal shape | circle | `circle()` tunnels; `inset()` square reveals a rectangular aperture |+| Duration | 1.2s | Long enough to read as travel; too short becomes a plain wipe |+| Easing | ease-in | `ease-in` = diving in, `ease-out` = pulling back, `ease-in-out` = smooth throughout |+| End radius | 150% | Must exceed 100% so the circle reaches the stage corners |+| Origin (px, py) | portal center | Where the clip expands from; measured live from the clicked element |++## Production notes+- **Force the reflow.** Without reading `offsetHeight` (or another layout property) between the zero-radius clip and the transition, the browser coalesces both writes and the page appears instantly at full size. The reflow read is what makes the growth animate.+- **Corner coverage.** A `circle(100%)` leaves the four corners unclipped mid-animation. Use ~150%, or compute the exact distance to the farthest corner if you need the reveal to finish precisely as it touches the last pixel.+- **`clip-path` compositing.** Animating `clip-path` is GPU-friendly but not free on low-end devices at large sizes. Keep the clipped element's paint area reasonable and avoid stacking it with heavy blur or shadow filters.+- **Library equivalents.** The View Transitions API is the natural fit — animate `clip-path` on `::view-transition-new(root)` from a pinhole at the click point for the same effect natively. GSAP animates `clipPath` strings directly; Framer Motion animates the `clipPath` style prop. This is also a common shader/WebGL reveal, but clip-path covers the DOM case without a canvas.++## See also+- [Zoom Transition](../zoom-transition/) — scales the whole page rather than clipping a window+- [Shared Element Transition](../shared-element-transition/) — an element grows into the next page's layout+- [Flash / Light Leak](../flash-transition/) — another reveal that hides the swap behind an overlay+- [Morph Transition](../morph-transition/) — reshapes an element between states instead of clippingdiff --git a/animations/03-page-transitions/shared-element-transition/README.md b/animations/03-page-transitions/shared-element-transition/README.mdnew file mode 100644index 00000000..efae23b1--- /dev/null+++ b/animations/03-page-transitions/shared-element-transition/README.md@@ -0,0 +1,56 @@+# Shared Element Transition++## What it is+A shared element transition keeps one piece of content visually continuous as the interface changes around it — a grid thumbnail grows and repositions into a detail-page hero rather than the two views cross-fading. It creates the feeling that the user moves *with* the content instead of jumping to a new screen. The demo implements it with the FLIP technique: measure the element's start and end rectangles, then animate a clone between them.++## When to use it+- Thumbnail-to-detail navigation in galleries, product grids, and media libraries+- Card-to-modal expansions where the card becomes the modal header+- Any place where the same object exists in both the "before" and "after" view and you want to preserve identity+- Mobile app-style navigation where spatial continuity aids orientation++## How it works+FLIP stands for First, Last, Invert, Play. Record the thumbnail's rectangle (First), reveal the destination and read the hero's rectangle (Last), position a fixed clone at the start rect, then on the next frame transition it to the end rect (Invert then Play):++```js+function openDetail(i){+ const thumbRect = thumbEls[i].getBoundingClientRect(); // FIRST+ detail.classList.add('active');+ const heroRect = detailHero.getBoundingClientRect(); // LAST+ // place clone at the thumb's position/size+ flipEl.style.cssText =+ `background:${p.bg};width:${thumbRect.width}px;height:${thumbRect.height}px;`++ `top:${thumbRect.top}px;left:${thumbRect.left}px;transition:none;display:block`;+ requestAnimationFrame(()=>requestAnimationFrame(()=>{ // PLAY+ flipEl.style.transition = `all ${dur}ms ${easeSel.value}`;+ flipEl.style.top = heroRect.top+'px';+ flipEl.style.left = heroRect.left+'px';+ flipEl.style.width = heroRect.width+'px';+ flipEl.style.height = heroRect.height+'px';+ flipEl.style.borderRadius = '0';+ }));+}+```++The real grid fades out while the clone travels, and the detail body fades in slightly later (`dur*0.6` delay) so the hero has arrived before its text appears. The double `requestAnimationFrame` guarantees the browser paints the start rect before the transition begins — without it the clone would jump straight to the end.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Duration | 500ms | Travel time of the morphing clone; 300–600ms feels responsive without dragging |+| Easing | `cubic-bezier(.2,.7,.3,1)` | "Smooth"; a springy `cubic-bezier(.34,1.56,.64,1)` adds overshoot on arrival |+| Grid fade | `dur*0.4` | Outgoing grid opacity fade, run concurrently with the clone |+| Body fade delay | `dur*0.6` | Detail text appears after the hero settles, staggering the reveal |++## Production notes+- **Read then write** — batch all `getBoundingClientRect()` reads before you touch styles. Interleaving reads and writes causes layout thrashing that stutters the animation.+- **The clone is `position:fixed`** with `will-change:transform`, so it animates on the compositor and ignores the scroll/layout of the pages underneath it.+- **Fixed positioning uses viewport coordinates**, which is why the demo reads `getBoundingClientRect()` directly. If your clone lives inside a transformed or scrolled ancestor, offsets must be adjusted.+- **Reduced motion** skips the clone entirely and snaps the detail view in.+- **Library equivalents**: the View Transitions API does this natively by giving both elements the same `view-transition-name`. Framer Motion's `layoutId` and shared `<motion.*>` elements automate FLIP; Next.js and GSAP's Flip plugin offer the same measure-invert-play primitive.++## See also+- [View Transitions API](../view-transitions-api/) — the browser-native way to share an element via `view-transition-name`+- [FLIP Technique](../flip-technique/) — the measure-invert-play primitive on its own+- [Portal Zoom](../portal-zoom/) — a related expand-from-source effect+- [Morph Transition](../morph-transition/) — continuity via shape interpolation rather than positiondiff --git a/animations/03-page-transitions/slide-transition/README.md b/animations/03-page-transitions/slide-transition/README.mdnew file mode 100644index 00000000..7e9ed0d3--- /dev/null+++ b/animations/03-page-transitions/slide-transition/README.md@@ -0,0 +1,57 @@+# Slide Transition++## What it is+A slide transition moves the outgoing page off one edge of the viewport while the incoming page slides in from the opposite edge, so the two travel together like panels on a track. When the direction is tied to navigation intent — forward slides left, back slides right — it gives users a spatial map of where they are in a flow. The demo mirrors the iOS and Android convention and also offers fixed left/right and vertical modes.++## When to use it+- Multi-step flows: onboarding, checkout, wizards where "next" and "back" have a clear direction+- Mobile-style navigation stacks where pushing and popping screens should feel spatial+- Carousels and paged content with an inherent left-to-right order+- Anywhere the direction of motion should reinforce the direction of navigation++## How it works+Direction is derived from whether the target index is greater or less than the current one; forward returns `-1` (slide left), back returns `+1` (slide right). The new page is parked off-screen on the opposite side, then both pages transition their `transform` together in the same direction:++```js+function getDir(prev,next){+ const m=dirMode.value;+ if(m==='ltr')return 1; if(m==='rtl')return -1; if(m==='vertical')return 2;+ return next>prev ? -1 : 1; // auto: forward = left(-1), back = right(+1)+}++function doTransition(prev,next){+ const d=getDir(prev,next), dir=Math.abs(d)===2?'Y':'X', sign=d<0?-1:1;+ newEl.style.transition='none';+ newEl.style.transform=`translate${dir}(${sign*-100}%)`; // park off-screen, opposite edge+ requestAnimationFrame(()=>requestAnimationFrame(()=>{+ oldEl.style.transition=`transform ${dur}ms ${easeSel.value}`;+ newEl.style.transition=`transform ${dur}ms ${easeSel.value} ${stagger}ms`;+ oldEl.style.transform=`translate${dir}(${sign*100}%)`; // both move the same way+ newEl.style.transform='translate(0,0)';+ }));+}+```++Because both pages animate `transform` in the same direction and by the same 100%, they stay locked edge-to-edge as they move — the compositor handles it entirely, which is why `will-change:transform` is set on every page. A stagger control adds an optional delay on the incoming page so it trails the outgoing one slightly.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Direction mode | Auto | Auto derives direction from navigation; ltr/rtl/vertical force a fixed axis |+| Duration | 500ms | Slide length; 300–500ms matches native feel, longer drags |+| Easing | `cubic-bezier(.2,.7,.3,1)` | "Smooth" decel; springy adds a slight settle at the end |+| Stagger | 0ms | Delay on the incoming page so it trails the outgoing one |++## Production notes+- **Animate `transform: translate`, never `left`/`right`** — translate runs on the compositor and stays at 60fps; positional properties trigger layout on every frame.+- **The double `requestAnimationFrame`** is required: it lets the browser paint the off-screen start position before the transition begins, otherwise the new page jumps straight in with no slide.+- **Off-screen pages keep `pointer-events` disabled** until active, so parked panels don't intercept taps.+- **Match direction to platform expectation.** On mobile, forward-left / back-right is muscle memory; inverting it disorients users. The auto mode encodes this.+- **Reduced motion** toggles the `.active` class and clears transforms with no slide.+- **Library equivalents**: the View Transitions API expresses this with slide keyframes on `::view-transition-old/new`. Framer Motion's `AnimatePresence` with `x` variants, React Router transition libraries, and GSAP's `xPercent` tweens all implement the same paired-translate.++## See also+- [View Transitions API](../view-transitions-api/) — includes a slide style built on the same idea+- [Zoom Transition](../zoom-transition/) — depth-based motion instead of lateral+- [Crossfade](../crossfade/) — the non-directional alternative+- [Elastic Transition](../elastic-transition/) — a springy take on directional motiondiff --git a/animations/03-page-transitions/view-transitions-api/README.md b/animations/03-page-transitions/view-transitions-api/README.mdnew file mode 100644index 00000000..33d97d85--- /dev/null+++ b/animations/03-page-transitions/view-transitions-api/README.md@@ -0,0 +1,60 @@+# View Transitions API++## What it is+The View Transitions API is a browser feature that animates between two DOM states without you having to coordinate the old and new elements by hand. You call `document.startViewTransition()` and pass a callback that mutates the DOM; the browser snapshots the page before and after, then cross-fades or otherwise animates between the two snapshots. The choreography is customized entirely through CSS pseudo-elements, so the same JavaScript can drive a fade, a slide, or a zoom.++## When to use it+- Same-document navigation in SPAs where you swap page content in place+- Multi-page navigation where you want a native-feeling transition between full documents (with the cross-document variant)+- Cases where the before/after DOM is complex and hand-animating each element would be error-prone+- When you want the transition style to be a CSS concern, decoupled from the navigation logic++## How it works+Wrap the DOM mutation in `startViewTransition()`. The browser captures the current frame, runs the callback, captures the new frame, and animates between them. A named region — set with `view-transition-name` — is tracked as its own snapshot pair, and CSS pseudo-elements animate the old and new captures independently:++```js+async function navigate(next){+ if(next===current||animating)return;+ const prev=current;current=next;+ document.documentElement.dataset.vt = style==='crossfade' ? '' : style;+ if(supportsVT){+ const t = document.startViewTransition(()=>switchPage(prev,next));+ await t.finished;+ }else{+ /* manual opacity fallback */+ }+}+```++```css+.page-area{ view-transition-name: page-content; }+/* Suppress the default root cross-fade; only page-content animates */+::view-transition-old(root),::view-transition-new(root){ animation:none }+::view-transition-old(page-content){ animation:vt-out var(--vt-dur) var(--vt-ease) both }+::view-transition-new(page-content){ animation:vt-in var(--vt-dur) var(--vt-ease) both }+@keyframes vt-out{ from{opacity:1} to{opacity:0} }+@keyframes vt-in { from{opacity:0} to{opacity:1} }+```++Switching the `data-vt` attribute swaps in a different keyframe set (slide, zoom, or a rotate-based custom style), so one code path produces four distinct transitions. `t.finished` resolves when the animation completes, which the demo awaits to gate re-entry.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| `--vt-dur` | 500ms | Snapshot animation length; under ~150ms reads as an instant swap |+| `--vt-ease` | ease-in-out | Timing curve applied to both old and new pseudo-elements |+| `view-transition-name` | `page-content` | Names the tracked region; each name animates as its own snapshot pair |+| Transition style | crossfade | Selects the keyframe set (crossfade / slide / zoom / custom rotate) |++## Production notes+- **Feature-detect** with `'startViewTransition' in document` and fall back to a manual opacity cross-fade — the demo does exactly this so unsupported browsers still transition.+- **Suppress the root animation** (`::view-transition-old(root)`) when you only want a sub-region to animate; otherwise the whole page cross-fades underneath your named region.+- **Every `view-transition-name` must be unique** on the page at capture time. Two elements sharing a name in the same snapshot throws and aborts the transition.+- **Honor reduced motion** — the demo drops straight to `switchPage()` with no animation when `prefers-reduced-motion: reduce` is set.+- **Library equivalents**: Astro's `<ViewTransitions />` and Next.js's experimental view-transition support wrap this API for cross-document navigation. Barba.js and Swup predate it and polyfill the same idea with manual snapshotting; on supported browsers you often no longer need them.++## See also+- [Crossfade](../crossfade/) — the default View Transitions style, built manually for comparison+- [Slide Transition](../slide-transition/) — the slide keyframe set as a standalone technique+- [Zoom Transition](../zoom-transition/) — the zoom keyframe set as a standalone technique+- [Shared Element Transition](../shared-element-transition/) — continuity for a single element rather than the whole pagediff --git a/animations/03-page-transitions/zoom-transition/README.md b/animations/03-page-transitions/zoom-transition/README.mdnew file mode 100644index 00000000..387a09df--- /dev/null+++ b/animations/03-page-transitions/zoom-transition/README.md@@ -0,0 +1,54 @@+# Zoom Transition++## What it is+A zoom transition combines a scale change with an opacity cross-fade so pages appear to advance or recede through depth rather than sliding across a plane. The direction of the scale carries meaning: zooming in feels like arriving or drilling into content, zooming out like backing away, and a pull-through — where the new page rushes in oversized and settles — feels like traveling through space. The demo exposes all three variants and reports the live scale of each page.++## When to use it+- Drilling into detail from an overview, where zoom-in reinforces "going deeper"+- Dismissing or backing out of a view, where zoom-out signals departure+- Hero or splash moments where a pull-through adds a sense of momentum+- Modal and lightbox reveals that should feel like the content comes forward++## How it works+Each variant is a set of four scale values — `[oldStart, oldEnd, newStart, newEnd]`. The pages start at their "start" scales with the new one transparent, then on the next frame both transition their `transform` and `opacity` to the "end" state simultaneously:++```js+const V={+ 'zoom-in': [1, 0.9, 0.75, 1], // new page grows from 0.75 → 1 as old shrinks away+ 'zoom-out':[1, 1.2, 1, 1], // old page enlarges past the frame and fades+ 'pull': [1, 0.7, 1.3, 1], // new rushes in from 1.3, old recedes to 0.7+}[variant];++o.style.transition='none'; n.style.transition='none';+o.style.transform=`scale(${V[0]})`;+n.style.opacity='0'; n.style.transform=`scale(${V[2]})`; n.classList.add('active');+requestAnimationFrame(()=>requestAnimationFrame(()=>{+ o.style.transition=t; n.style.transition=t; // t = `all ${dur}ms ${ease}`+ o.style.opacity='0'; o.style.transform=`scale(${V[1]})`;+ n.style.opacity='1'; n.style.transform=`scale(${V[3]})`;+}));+```++Because the incoming and outgoing scales differ per variant, the same code path produces three distinct spatial feelings. The opacity cross-fade runs alongside the scale so neither page ever appears hard-edged over the other, and the double `requestAnimationFrame` ensures the start scale is painted before the transition kicks off.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Variant | Zoom in | Selects the four-value scale set (in / out / pull-through) |+| Duration | 550ms | Length of the combined scale + fade |+| Easing | `cubic-bezier(.2,.7,.3,1)` | "Smooth"; springy overshoots the end scale for a settle |+| New start scale | 0.75 (zoom-in) | How far the incoming page grows from — larger gaps read as deeper travel |++## Production notes+- **Animate `transform: scale`, not `width`/`height`.** Scale is composited and cheap; animating dimensions relays out the page every frame and drops frames.+- **Set `transform-origin` deliberately.** The demo scales from center; a zoom that should originate from a tapped card needs its origin set to that point, otherwise the growth feels detached from the trigger.+- **Fade alongside the scale.** Scaling without the opacity cross-fade leaves a hard edge where the two pages overlap; the paired fade hides the seam.+- **Springy easing can overshoot past scale 1** and momentarily clip content at the stage edge — keep overshoot modest or add padding.+- **Reduced motion** swaps pages by opacity only, skipping the scale.+- **Library equivalents**: the View Transitions API ships a zoom style via `::view-transition` scale keyframes. Framer Motion's `scale` variants in `AnimatePresence`, GSAP's `scale` tweens, and Next.js transitions all express the same scale-plus-fade.++## See also+- [View Transitions API](../view-transitions-api/) — includes a zoom style built the same way+- [Portal Zoom](../portal-zoom/) — zoom anchored to a specific source element+- [Slide Transition](../slide-transition/) — lateral motion instead of depth+- [Shared Element Transition](../shared-element-transition/) — scaling a single element for continuitydiff --git a/animations/04-micro-interactions/README.md b/animations/04-micro-interactions/README.mdindex 93cb66e1..90b5fd9d 100644--- a/animations/04-micro-interactions/README.md+++ b/animations/04-micro-interactions/README.md@@ -10,7 +10,10 @@ Short, user-triggered animations that provide feedback, confirm actions, and com| [Click / Tap Ripple](click-ripple/) | Ripple from exact click point — Material Design's tactile confirmation || [Focus Ring Animation](focus-ring/) | Animated outline on keyboard Tab — :focus-visible for keyboard users only || [Button Press Scale](button-press-scale/) | Scales down on press, springs back on release — asymmetric timing |+| [Magnetic Button](magnetic-button/) | Button leans toward the cursor within a radius, label lagging for parallax || [Toggle / Switch Slide](toggle-switch/) | Pill slides between on/off — smooth cubic-bezier for weighted feel |+| [Heart / Like Burst](heart-burst/) | Heart pops and fills while small hearts burst outward on canvas |+| [Success Confetti](success-confetti/) | Canvas confetti burst on completion — rotating rectangles with gravity || [Skeleton Loader](skeleton-loader/) | Pulsing placeholder blocks while real content loads || [Shimmer Effect](shimmer-effect/) | Gradient sweep across skeleton placeholders || [Loading Spinner](loading-spinner/) | Six spinner variants — ring, orbit, arc, bounce, pulse, square |@@ -23,6 +26,8 @@ Short, user-triggered animations that provide feedback, confirm actions, and com| [Modal Expand](modal-expand/) | Modal scales from trigger button position — spatial continuity || [Accordion Open/Close](accordion/) | Height 0 → auto: JS measured vs CSS grid-template-rows || [Cursor Follower](cursor-follower/) | Lerp-lagged cursor + mix-blend-mode: difference inversion |+| [Error Shake](error-shake/) | Invalid field shakes with a decaying wobble and flashes red — the universal "no" |+| [Swipe to Dismiss](swipe-to-dismiss/) | Drag past a threshold to fling a card away as its row collapses — pointer-driven, touch-ready |## Key conceptsdiff --git a/animations/04-micro-interactions/error-shake/README.md b/animations/04-micro-interactions/error-shake/README.mdnew file mode 100644index 00000000..14bfa7ef--- /dev/null+++ b/animations/04-micro-interactions/error-shake/README.md@@ -0,0 +1,60 @@+# Error Shake++## What it is+An error shake is a validation-feedback pattern: when a user submits an invalid value, the offending field wobbles horizontally a few times and settles back to center, usually alongside a red border and an inline message. The motion is short, decaying, and purely on the X axis — a visual analogue of a human shaking their head "no."++## When to use it+- Login and sign-up forms on a failed or empty submit+- Inline field validation (wrong format, out-of-range value, mismatched confirmation)+- One-time password / PIN entry where a wrong code should be rejected without navigating away+- Any single-field rejection where you want feedback *at the field*, not in a separate toast++## How it works+The field is animated by toggling an `error` class that applies a `@keyframes` translateX wobble. The keyframe swings the element left and right with **decaying amplitude**, then returns to `translateX(0)`. Because only `transform` is animated, it stays on the compositor and never triggers layout:++```css+@keyframes shake {+ 10%,90% { transform: translateX(calc(var(--shake-x) * -1)); }+ 20%,80% { transform: translateX(calc(var(--shake-x) * 1)); }+ 30%,50%,70% { transform: translateX(calc(var(--shake-x) * -0.6)); }+ 40%,60% { transform: translateX(calc(var(--shake-x) * 0.6)); }+ 100% { transform: translateX(0); }+}+.field.error input { border-color: var(--err); animation: shake var(--shake-dur) cubic-bezier(.36,.07,.19,.97) both; }+```++The one JS gotcha: re-adding the class on an element that already has it won't replay the animation. Force a reflow between removing and re-adding so the browser restarts it:++```js+function shake(text){+ field.classList.remove('error','ok');+ void field.offsetWidth; // reflow -> animation restarts+ msg.textContent = text;+ field.classList.add('error');+}+```++A decaying shake reads as "no" universally because it *returns to origin*. Motion that ends where it began signals rejection — nothing was committed. Contrast a slide or a checkmark, which move to a new state and signal progress. The decay (large swings shrinking to small) mimics the physics of a real headshake and a damped spring, so it feels natural rather than like a glitch.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Shake intensity | 8px | Peak X displacement. Under 4px is barely legible; over ~16px feels violent |+| Oscillations | 6 | Number of left-right swings. 4–6 reads as a headshake; more feels frantic |+| Duration | 400ms | Total wobble time. Under 250ms feels twitchy; over 600ms drags |+| Easing | `cubic-bezier(.36,.07,.19,.97)` | Snappy in/out so swings feel sharp, not floaty |+| Error color | `#f4515b` | Border + message color; pair with text, never rely on color alone |++## Production notes+- **Don't rely on motion or color alone.** The shake and red border are reinforcement; the inline text message is what conveys *why* it failed. Color-blind and reduced-motion users need the words.+- **Reduced motion**: gate the shake behind `@media (prefers-reduced-motion: reduce)` and disable the animation there — the red border plus message still communicates the failure without any movement.+- **Restart trick**: the reflow (`void el.offsetWidth`) is required for repeated failures. Alternatively, listen for `animationend` and remove the class, or use the Web Animations API (`el.animate(...)`) which restarts cleanly on every call.+- **Debounce rapid submits** so a mashed submit button doesn't stack animations; the class-toggle + reflow pattern already coalesces to one run.+- **`prefers-reduced-motion` at the JS layer**: if you drive the shake with the WAAPI instead of CSS, check the media query in JS and skip `.animate()` when reduce is set.+- **Library equivalents**: Framer Motion expresses this as `animate={{ x: [0,-8,8,-5,5,0] }}` on a keyframe array; GSAP ships a dedicated `RoughEase` and you can also `gsap.fromTo(el,{x:-8},{x:0,ease:'elastic'})`. Both are the same translateX-keyframe idea with nicer restart ergonomics.++## See also+- [Form Field Morph](../form-field-morph/) — the valid-state transition counterpart to a rejection+- [Focus Ring](../focus-ring/) — the other key input-affordance micro-interaction+- [Button Press Scale](../button-press-scale/) — press feedback on the submit button that triggers validation+- [Checkmark Draw](../checkmark-draw/) — the "yes" success motion that a shake is the opposite ofdiff --git a/animations/04-micro-interactions/error-shake/index.html b/animations/04-micro-interactions/error-shake/index.htmlnew file mode 100644index 00000000..0caf33fe--- /dev/null+++ b/animations/04-micro-interactions/error-shake/index.html@@ -0,0 +1,154 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Error Shake</title>+ <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}+ @font-face{font-family:'PlexMono';src:url('../../../assets/fonts/plex-400.woff2') format('woff2');font-weight:400;font-display:swap}+ @font-face{font-family:'PlexMono';src:url('../../../assets/fonts/plex-500.woff2') format('woff2');font-weight:500;font-display:swap}+ :root{--bg:#0b0b0d;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#ff9d5c;--ui-text:#f4f4f2;--ui-muted:#77777e;--disp:'Bricolage','Arial Narrow',sans-serif;--mono:'PlexMono',ui-monospace,Menlo,Consolas,monospace;--stage-h:620px;--err:#f4515b;--ok:#3fb950;--shake-x:8px;--shake-osc:6;--shake-dur:400ms}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:var(--mono);-webkit-font-smoothing:antialiased;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ 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;background:var(--bg);display:flex;align-items:center;justify-content:center;padding:32px}+ /* Login card */+ .card{width:100%;max-width:320px;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:12px;padding:24px;display:flex;flex-direction:column;gap:14px}+ .card h2{font-family:var(--disp);font-weight:700;font-size:15px}+ .card .hint{font-size:10px;color:var(--ui-muted);line-height:1.5}+ .field{display:flex;flex-direction:column;gap:6px}+ .field label{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-muted)}+ .field input{background:var(--bg);border:1.5px solid var(--ui-border);color:var(--ui-text);font-family:var(--mono);font-size:13px;padding:11px 12px;border-radius:7px;width:100%;min-height:44px;outline:none;transition:border-color .18s}+ .field input:focus{border-color:var(--ui-accent)}+ /* Error state: red border + shake keyframe */+ .field.error input{border-color:var(--err)}+ .field.error input{animation:shake var(--shake-dur) cubic-bezier(.36,.07,.19,.97) both}+ .msg{font-size:10.5px;min-height:14px;color:var(--err);opacity:0;transform:translateY(-2px);transition:opacity .18s,transform .18s}+ .field.error .msg{opacity:1;transform:none}+ .field.ok input{border-color:var(--ok)}+ .field.ok .msg{opacity:1;transform:none;color:var(--ok)}+ /* The decaying horizontal wobble. translateX only -> compositor-friendly. */+ @keyframes shake{+ 10%,90%{transform:translateX(calc(var(--shake-x) * -1))}+ 20%,80%{transform:translateX(calc(var(--shake-x) * 1))}+ 30%,50%,70%{transform:translateX(calc(var(--shake-x) * -0.6))}+ 40%,60%{transform:translateX(calc(var(--shake-x) * 0.6))}+ 100%{transform:translateX(0)}+ }+ .submit{background:var(--ui-accent);border:none;color:#1a0f08;font-family:var(--disp);font-weight:700;font-size:12px;padding:13px;border-radius:7px;cursor:pointer;min-height:44px;transition:filter .15s}+ @media(hover:hover){.submit:hover{filter:brightness(1.08)}}+ .submit:active{filter:brightness(.94)}+ 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)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sval{width:52px;text-align:right;color:var(--ui-text)}+ .div{height:1px;background:var(--ui-border)}+ .replay{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){.replay:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:auto}.stage{height:auto;min-height:420px}}+ @media(prefers-reduced-motion:reduce){.field.error input{animation:none!important}}+ </style>+</head>+<body>+<header>+ <h1>Error Shake</h1>+ <p>Invalid input triggers a decaying horizontal wobble plus a red border — a universal "no".</p>+</header>+<div class="layout">+ <div class="stage">+ <form class="card" id="login" novalidate>+ <h2>Sign in</h2>+ <p class="hint">Password is <b>letmein</b>. Try a wrong value (or submit empty) to see the shake.</p>+ <div class="field" id="field">+ <label for="pw">Password</label>+ <input type="password" id="pw" autocomplete="off" placeholder="••••••••">+ <span class="msg" id="msg"></span>+ </div>+ <button class="submit" type="submit">Sign in</button>+ </form>+ </div>+ <aside>+ <p class="note">A shake decays — big swings settle to small ones, then stop. That deceleration reads as a headshake: motion that returns to origin says "denied," not "progress."</p>+ <div class="lbl">Shake intensity</div>+ <div class="sr"><input type="range" id="int-sl" min="2" max="20" value="8" step="1"><span class="sval" id="int-v">8px</span></div>+ <div class="lbl">Oscillations</div>+ <div class="sr"><input type="range" id="osc-sl" min="2" max="8" value="6" step="1"><span class="sval" id="osc-v">6</span></div>+ <div class="lbl">Duration</div>+ <div class="sr"><input type="range" id="dur-sl" min="200" max="800" value="400" step="20"><span class="sval" id="dur-v">400ms</span></div>+ <div class="div"></div>+ <button class="replay" id="replay">↺ Replay shake</button>+ </aside>+</div>+<script>+ const form=document.getElementById('login');+ const field=document.getElementById('field');+ const input=document.getElementById('pw');+ const msg=document.getElementById('msg');+ const root=document.documentElement.style;+ const PASSWORD='letmein';++ // Building the keyframe from the oscillation count keeps the demo honest:+ // more oscillations = more decaying swings written into one @keyframes.+ function buildShake(count){+ const sheet=document.styleSheets[0];+ // find and drop the old shake rule+ for(let i=sheet.cssRules.length-1;i>=0;i--){+ if(sheet.cssRules[i].name==='shake'){sheet.deleteRule(i);break;}+ }+ let steps='0%{transform:translateX(0)}';+ for(let i=1;i<=count;i++){+ const pos=(i/(count+1))*100;+ const dir=i%2?-1:1;+ const decay=(1-i/(count+1)).toFixed(3); // amplitude shrinks toward the end+ steps+=`${pos.toFixed(2)}%{transform:translateX(calc(var(--shake-x) * ${(dir*decay).toFixed(3)}))}`;+ }+ steps+='100%{transform:translateX(0)}';+ sheet.insertRule(`@keyframes shake{${steps}}`,sheet.cssRules.length);+ }++ function clearState(){field.classList.remove('error','ok');}++ function shake(text){+ clearState();+ // reflow forces the animation to restart even on repeated failures+ void field.offsetWidth;+ msg.textContent=text;+ field.classList.add('error');+ }++ form.addEventListener('submit',e=>{+ e.preventDefault();+ const v=input.value.trim();+ if(!v){shake('Password is required.');input.focus();return;}+ if(v!==PASSWORD){shake('Incorrect password. Try again.');input.select();return;}+ clearState();+ msg.textContent='Welcome back — signed in.';+ field.classList.add('ok');+ });+ input.addEventListener('input',clearState);++ document.getElementById('int-sl').addEventListener('input',e=>{+ document.getElementById('int-v').textContent=e.target.value+'px';+ root.setProperty('--shake-x',e.target.value+'px');+ });+ document.getElementById('osc-sl').addEventListener('input',e=>{+ document.getElementById('osc-v').textContent=e.target.value;+ buildShake(+e.target.value);+ });+ document.getElementById('dur-sl').addEventListener('input',e=>{+ document.getElementById('dur-v').textContent=e.target.value+'ms';+ root.setProperty('--shake-dur',e.target.value+'ms');+ });+ document.getElementById('replay').addEventListener('click',()=>shake('Incorrect password. Try again.'));++ buildShake(6);+</script>+</body>+</html>diff --git a/animations/04-micro-interactions/heart-burst/README.md b/animations/04-micro-interactions/heart-burst/README.mdnew file mode 100644index 00000000..980d2b98--- /dev/null+++ b/animations/04-micro-interactions/heart-burst/README.md@@ -0,0 +1,61 @@+# Heart / Like Burst++## What it is+A like button that celebrates the moment of liking. Tapping toggles the liked state: the heart plays a pop — a quick scale overshoot — and fills with color, while a short-lived spray of small hearts and dots bursts outward from its center and fades. Un-liking simply reverts the color with no burst. The pattern was popularized by Twitter's heart and is now a standard reward micro-interaction.++## When to use it+- Like / favorite / react buttons in feeds, galleries, and comment threads+- Any single binary "positive" action worth a small dopamine reward+- Save-to-collection or bookmark buttons where you want the save to feel earned+- Not for destructive or neutral toggles — the celebration implies approval++## How it works+The heart itself is an inline SVG whose fill color transitions on a `.on` class, plus a keyframed pop for the overshoot. The burst is a particle system drawn on a `<canvas>` overlay stretched across the stage. On like, you spawn N particles at the heart's center, each with a random angle and velocity; every frame you advance them, apply gravity, and decrement life until they fade out:++```js+function spawn() {+ const b = btn.getBoundingClientRect(), s = stage.getBoundingClientRect();+ const ox = b.left + b.width/2 - s.left, oy = b.top + b.height/2 - s.top;+ for (let i = 0; i < pCount; i++) {+ const a = Math.random() * Math.PI * 2, v = spread * (0.5 + Math.random()*0.5) / 12;+ particles.push({ x: ox, y: oy, vx: Math.cos(a)*v, vy: Math.sin(a)*v - 1, life: 1, /* ... */ });+ }+ if (!raf) raf = requestAnimationFrame(tick);+}++function tick() {+ ctx.clearRect(0, 0, cv.width, cv.height);+ particles = particles.filter(p => p.life > 0);+ for (const p of particles) {+ p.x += p.vx; p.y += p.vy; p.vy += 0.12; p.life -= 0.022; // move, gravity, fade+ ctx.globalAlpha = p.life;+ /* draw heart or dot at p.x, p.y */+ }+ raf = particles.length ? requestAnimationFrame(tick) : null;+}+```++The `-1` bias on initial `vy` makes the burst lean upward before gravity pulls it down. The pop is retriggered by removing and re-adding the animation class (`btn.classList.remove('pop'); void btn.offsetWidth; btn.classList.add('pop')`) so repeated likes always re-fire.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Particle count | 18 | More reads as bigger celebration; above ~40 it gets busy and costs frames |+| Burst spread | 90px | Scales initial velocity, so how far particles travel before fading |+| Pop keyframes | 0.8 → 1.25 → 0.92 → 1 | The overshoot curve. Peak >1.3 looks rubbery |+| Fade rate | 0.022/frame | Life drain per frame — sets burst lifetime (~700ms at 60fps) |++## Production notes+- **Canvas over DOM particles**: 18–40 short-lived DOM `<span>`s per tap creates layout/GC churn if the user spams the button. One canvas with an array of plain objects stays flat and cheap.+- **Idle the loop**: stop `requestAnimationFrame` when `particles.length === 0` and restart it on the next spawn. A permanently running rAF wastes battery for a control that fires occasionally.+- **DPR scaling**: size the canvas backing store by `devicePixelRatio` (capped at ~2) and `ctx.setTransform(dpr,0,0,dpr,0,0)` so hearts stay crisp on retina without over-allocating on 3x phones.+- **Reduced motion**: skip the pop and the burst entirely — just toggle the fill color. The state change must still be conveyed, only the celebration is dropped.+- **Accessibility**: back the button with `aria-pressed` and toggle it with the state; the visual burst is decorative and should be `aria-hidden`.+- **canvas-confetti**: for a drop-in radial burst, `confetti({ particleCount, spread, origin })` gives you the same physics without hand-rolling the loop.+- **Framer Motion / Lottie**: Framer's `AnimatePresence` can drive DOM particles for small counts; many production apps instead ship a pre-rendered Lottie burst for pixel-consistent art across platforms.++## See also+- [Button Press Scale](../button-press-scale/) — the scale-overshoot mechanic behind the heart pop+- [Badge Pulse](../badge-pulse/) — another attention-reward micro-interaction+- [Checkmark Draw](../checkmark-draw/) — success feedback without a particle system+- [Click / Tap Ripple](../click-ripple/) — a calmer tactile confirmation from the tap pointdiff --git a/animations/04-micro-interactions/heart-burst/index.html b/animations/04-micro-interactions/heart-burst/index.htmlnew file mode 100644index 00000000..4a74c708--- /dev/null+++ b/animations/04-micro-interactions/heart-burst/index.html@@ -0,0 +1,121 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Heart / Like Burst</title>+ <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:'PlexMono';src:url('../../../assets/fonts/plex-400.woff2') format('woff2');font-weight:400;font-display:swap}+ :root{--bg:#0b0b0d;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#ff9d5c;--ui-text:#f4f4f2;--ui-muted:#77777e;--like:#ff5470;--disp:'Bricolage','Arial Narrow',sans-serif;--mono:'PlexMono',ui-monospace,Menlo,Consolas,monospace;--stage-h:620px}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:var(--mono);-webkit-font-smoothing:antialiased;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-family:var(--disp);font-weight:700;font-size:clamp(16px,2.2vw,22px);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{position:relative;flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;background:var(--bg);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:20px;overflow:hidden;touch-action:manipulation}+ canvas{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}+ .like-wrap{position:relative;z-index:2}+ .like-btn{position:relative;background:none;border:none;cursor:pointer;width:96px;height:96px;display:flex;align-items:center;justify-content:center;-webkit-tap-highlight-color:transparent}+ .heart{width:64px;height:64px;color:var(--ui-muted);transition:color .2s;transform-origin:center}+ .heart path{transition:fill .2s}+ .like-btn.on .heart{color:var(--like)}+ /* Pop: overshoot scale keyframe applied on like */+ @keyframes pop{0%{transform:scale(1)}30%{transform:scale(.8)}55%{transform:scale(1.25)}75%{transform:scale(.92)}100%{transform:scale(1)}}+ .like-btn.pop .heart{animation:pop .5s cubic-bezier(.22,1,.36,1)}+ .count{font-size:12px;color:var(--ui-muted);z-index:2}+ .count b{color:var(--ui-text);font-family:var(--disp)}+ 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}+ .lbl2{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sval{width:52px;text-align:right;color:var(--ui-text)}+ .kv{display:flex;justify-content:space-between;font-size:10px;color:var(--ui-muted)}+ .kv .v{color:var(--ui-text)}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:auto}.stage{height:auto;min-height:420px}}+ @media(prefers-reduced-motion:reduce){.like-btn.pop .heart{animation:none}}+ </style>+</head>+<body>+<header>+ <h1>Heart / Like Burst</h1>+ <p>Tap to like — the heart pops and fills as a spray of small hearts bursts outward and fades, Twitter-style.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <canvas id="cv"></canvas>+ <div class="like-wrap">+ <button class="like-btn" id="btn" aria-pressed="false" aria-label="Like">+ <svg class="heart" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12 21s-7.5-4.9-10-9.3C.4 8.3 2 5 5.2 5c1.9 0 3.2 1 3.8 2 .6-1 1.9-2 3.8-2 3.2 0 4.8 3.3 3.2 6.7C19.5 16.1 12 21 12 21z"/></svg>+ </button>+ </div>+ <div class="count">Likes <b id="count">128</b></div>+ </div>+ <aside>+ <p class="note">The burst is a short-lived particle system on a canvas overlay. Each tap spawns N particles with random angle/velocity; gravity and fade retire them within ~700ms. Un-liking is silent.</p>+ <div class="lbl2">Particle Count</div>+ <div class="sr"><input type="range" id="cnt-sl" min="6" max="40" value="18" step="1"><span class="sval" id="cnt-v">18</span></div>+ <div class="lbl2">Burst Spread</div>+ <div class="sr"><input type="range" id="spr-sl" min="40" max="160" value="90" step="5"><span class="sval" id="spr-v">90px</span></div>+ <div class="div"></div>+ <div class="kv"><span>State</span><span class="v" id="state-v">Not liked</span></div>+ <div class="kv"><span>Live particles</span><span class="v" id="live-v">0</span></div>+ </aside>+</div>+<script>+const stage=document.getElementById('stage'),btn=document.getElementById('btn'),+ cv=document.getElementById('cv'),ctx=cv.getContext('2d'),countEl=document.getElementById('count');+const reduce=window.matchMedia('(prefers-reduced-motion: reduce)').matches;+let liked=false,count=128,particles=[],raf=null,dpr=Math.min(window.devicePixelRatio||1,2);+let pCount=18,spread=90;++function resize(){cv.width=stage.clientWidth*dpr;cv.height=stage.clientHeight*dpr;ctx.setTransform(dpr,0,0,dpr,0,0);}+resize();new ResizeObserver(resize).observe(stage);++function spawn(){+ const b=btn.getBoundingClientRect(),s=stage.getBoundingClientRect();+ const ox=b.left+b.width/2-s.left, oy=b.top+b.height/2-s.top;+ for(let i=0;i<pCount;i++){+ const a=Math.random()*Math.PI*2, v=spread*(0.5+Math.random()*0.5)/12;+ particles.push({x:ox,y:oy,vx:Math.cos(a)*v,vy:Math.sin(a)*v-1,life:1,size:4+Math.random()*5,+ hue:['#ff5470','#ff9d5c','#ffd166','#ff85a1'][i%4],heart:Math.random()>0.4});+ }+ if(!raf)raf=requestAnimationFrame(tick);+}+function tick(){+ ctx.clearRect(0,0,cv.width,cv.height);+ particles=particles.filter(p=>p.life>0);+ document.getElementById('live-v').textContent=particles.length;+ for(const p of particles){+ p.x+=p.vx;p.y+=p.vy;p.vy+=0.12;p.vx*=0.98;p.life-=0.022;+ ctx.globalAlpha=Math.max(p.life,0);ctx.fillStyle=p.hue;+ if(p.heart){drawHeart(p.x,p.y,p.size);}+ else{ctx.beginPath();ctx.arc(p.x,p.y,p.size*0.5,0,Math.PI*2);ctx.fill();}+ }+ ctx.globalAlpha=1;+ if(particles.length)raf=requestAnimationFrame(tick);else raf=null;+}+function drawHeart(x,y,s){+ ctx.save();ctx.translate(x,y);ctx.scale(s/24,s/24);ctx.beginPath();+ ctx.moveTo(0,6);ctx.bezierCurveTo(-12,-6,-6,-14,0,-6);ctx.bezierCurveTo(6,-14,12,-6,0,6);+ ctx.closePath();ctx.fill();ctx.restore();+}+btn.addEventListener('click',()=>{+ liked=!liked;+ btn.classList.toggle('on',liked);+ btn.setAttribute('aria-pressed',liked);+ document.getElementById('state-v').textContent=liked?'Liked':'Not liked';+ if(liked){+ count++;+ if(!reduce){btn.classList.remove('pop');void btn.offsetWidth;btn.classList.add('pop');spawn();}+ }else{count--;}+ countEl.textContent=count;+});+document.getElementById('cnt-sl').addEventListener('input',e=>{pCount=+e.target.value;document.getElementById('cnt-v').textContent=pCount;});+document.getElementById('spr-sl').addEventListener('input',e=>{spread=+e.target.value;document.getElementById('spr-v').textContent=spread+'px';});+</script>+</body>+</html>diff --git a/animations/04-micro-interactions/magnetic-button/README.md b/animations/04-micro-interactions/magnetic-button/README.mdnew file mode 100644index 00000000..62976b50--- /dev/null+++ b/animations/04-micro-interactions/magnetic-button/README.md@@ -0,0 +1,52 @@+# Magnetic Button++## What it is+A magnetic button is a call-to-action that appears attracted to the cursor: as the pointer enters an invisible radius around the button, the button translates a fraction of the way toward the pointer, and its label drifts a little further for a parallax feel. When the pointer leaves, the button springs back to rest. The effect is entirely a transform driven by pointer distance — the button never actually leaves its layout position.++## When to use it+- Hero CTAs on portfolio and landing pages, where a single button carries most of the attention+- Primary actions you want to feel responsive and "alive" without being noisy+- Award-style / agency sites where tactile pointer play is part of the brand+- Sparingly — one or two magnetic elements per view, not every button++## How it works+On every `pointermove` over the stage, you measure the vector from the button's center to the pointer. If the distance is within the activation radius, you translate the button by that vector scaled by a strength factor, with a falloff so the pull eases to zero at the radius edge. The inner label uses a smaller multiplier, so it lags behind the button body:++```js+stage.addEventListener('pointermove', e => {+ const s = stage.getBoundingClientRect(), b = btn.getBoundingClientRect();+ const bx = b.left + b.width/2 - s.left, by = b.top + b.height/2 - s.top;+ const dx = (e.clientX - s.left) - bx, dy = (e.clientY - s.top) - by;+ const dist = Math.hypot(dx, dy);+ if (dist < radius) {+ const pull = 1 - dist / radius; // 1 at center → 0 at edge+ const tx = dx * strength * pull, ty = dy * strength * pull;+ btn.style.transform = `translate(${tx}px, ${ty}px)`;+ lbl.style.transform = `translate(${tx*0.35}px, ${ty*0.35}px)`;+ } else { reset(); }+});+stage.addEventListener('pointerleave', reset); // spring home+```++The spring-back is just a CSS `transition: transform .55s cubic-bezier(.22,1,.36,1)` on the button — when JS clears the inline transform, the button eases home on its own. On touch devices (no hover), the magnet is skipped entirely and the button only does a press-scale on tap.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Magnet strength | 0.35 | Fraction of the cursor-distance the button travels. Above ~0.5 it feels loose and unglued |+| Activation radius | 160px | How far out the pull begins. Too large and the button reacts to distant, unrelated movement |+| Label multiplier | 0.35 | Extra travel on the inner label for parallax. 0 = no parallax; too high = label detaches |+| Return easing | `cubic-bezier(.22,1,.36,1)` | Slight overshoot on release reads as spring, not slide |++## Production notes+- **Gate on hover capability**: check `window.matchMedia('(hover: hover)').matches` and only bind the magnet on pointer devices. On touch, `pointermove` fires only while dragging, so the effect would feel broken — fall back to a plain press-scale.+- **Transform only**: animate `translate`, never `top`/`left`. The button stays on the compositor and the layout never reflows, so it holds 60fps even during rapid pointer movement.+- **Debounce is unnecessary but rAF helps**: for heavier scenes, batch the transform write inside a `requestAnimationFrame` so multiple `pointermove` events in one frame collapse to a single style write.+- **Reduced motion**: shorten the transition to a near-instant linear move so the button still tracks but without the springy overshoot.+- **GSAP**: `gsap.quickTo(btn, "x", {duration:.5, ease:"power3"})` is the idiomatic way to do this — it interpolates toward the target every frame instead of snapping, giving smoother lag for free.+- **Framer Motion**: drive a `useSpring` off the pointer offset and feed it into a `motion.button`'s `x`/`y`; the spring config replaces the CSS easing.++## See also+- [Button Press Scale](../button-press-scale/) — the tap feedback used as the touch fallback here+- [Hover State Animation](../hover-state/) — simpler, non-positional cursor feedback+- [Cursor Follower](../cursor-follower/) — the inverse idea: an element that chases the cursor across the whole pagediff --git a/animations/04-micro-interactions/magnetic-button/index.html b/animations/04-micro-interactions/magnetic-button/index.htmlnew file mode 100644index 00000000..1cda045e--- /dev/null+++ b/animations/04-micro-interactions/magnetic-button/index.html@@ -0,0 +1,115 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Magnetic Button</title>+ <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:'PlexMono';src:url('../../../assets/fonts/plex-400.woff2') format('woff2');font-weight:400;font-display:swap}+ :root{--bg:#0b0b0d;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#ff9d5c;--ui-text:#f4f4f2;--ui-muted:#77777e;--disp:'Bricolage','Arial Narrow',sans-serif;--mono:'PlexMono',ui-monospace,Menlo,Consolas,monospace;--stage-h:620px;--radius:160}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:var(--mono);-webkit-font-smoothing:antialiased;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-family:var(--disp);font-weight:700;font-size:clamp(16px,2.2vw,22px);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{position:relative;flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;background:var(--bg);display:flex;align-items:center;justify-content:center;overflow:hidden;touch-action:manipulation}+ /* Radius ring — purely visual, follows the button */+ .ring{position:absolute;width:calc(var(--radius)*2px);height:calc(var(--radius)*2px);border:1px dashed rgba(255,157,92,.35);border-radius:50%;pointer-events:none;opacity:0;transition:opacity .2s}+ .ring.show{opacity:1}+ .mag{position:relative;border:none;cursor:pointer;background:var(--ui-accent);color:#1a0e05;font-family:var(--disp);font-weight:700;font-size:clamp(15px,2vw,18px);letter-spacing:.01em;padding:20px 40px;min-height:56px;border-radius:40px;transition:transform .55s cubic-bezier(.22,1,.36,1);will-change:transform}+ .mag.pressed{transform:scale(.94)}+ .mag .lbl{display:inline-block;transition:transform .55s cubic-bezier(.22,1,.36,1);will-change:transform}+ .hint{position:absolute;bottom:18px;left:0;right:0;text-align:center;font-size:10px;color:var(--ui-muted);letter-spacing:.5px;pointer-events:none}+ 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}+ .lbl2{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sval{width:52px;text-align:right;color:var(--ui-text)}+ .tog-inp{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}+ .tog-inp input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}+ .kv{display:flex;justify-content:space-between;font-size:10px;color:var(--ui-muted)}+ .kv .v{color:var(--ui-text)}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:auto}.stage{height:auto;min-height:420px}}+ @media(prefers-reduced-motion:reduce){.mag,.mag .lbl{transition:transform .12s linear}}+ </style>+</head>+<body>+<header>+ <h1>Magnetic Button</h1>+ <p>A CTA that leans toward the cursor within a radius, its label lagging for parallax, then springs home on exit.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <div class="ring" id="ring"></div>+ <button class="mag" id="btn"><span class="lbl">Get Started</span></button>+ <div class="hint" id="hint">Move your cursor near the button</div>+ </div>+ <aside>+ <p class="note">Magnetism is pointer distance mapped to a translate. The button moves a fraction of the way to the cursor; the label moves further, so it appears to float above the surface.</p>+ <div class="lbl2">Magnet Strength</div>+ <div class="sr"><input type="range" id="str-sl" min="0" max="60" value="35" step="1"><span class="sval" id="str-v">0.35</span></div>+ <div class="lbl2">Activation Radius</div>+ <div class="sr"><input type="range" id="rad-sl" min="80" max="280" value="160" step="10"><span class="sval" id="rad-v">160px</span></div>+ <label class="tog-inp"><input type="checkbox" id="ring-tog"><span>Show radius ring</span></label>+ <div class="div"></div>+ <div class="kv"><span>Pull</span><span class="v" id="pull-v">0px</span></div>+ <div class="kv"><span>Input</span><span class="v" id="mode-v">—</span></div>+ </aside>+</div>+<script>+const stage=document.getElementById('stage'),btn=document.getElementById('btn'),+ lbl=btn.querySelector('.lbl'),ring=document.getElementById('ring'),hint=document.getElementById('hint');+const hasHover=window.matchMedia('(hover: hover)').matches;+let strength=0.35,radius=160;++document.getElementById('mode-v').textContent=hasHover?'pointer (magnet)':'touch (press)';++function reset(){+ btn.style.transform='';lbl.style.transform='';ring.style.left='';ring.style.top='';+ document.getElementById('pull-v').textContent='0px';+}++if(hasHover){+ stage.addEventListener('pointermove',e=>{+ const s=stage.getBoundingClientRect(),b=btn.getBoundingClientRect();+ // Button center relative to stage+ const bx=b.left+b.width/2-s.left, by=b.top+b.height/2-s.top;+ const px=e.clientX-s.left, py=e.clientY-s.top;+ const dx=px-bx, dy=py-by, dist=Math.hypot(dx,dy);+ ring.style.left=(bx-radius)+'px';ring.style.top=(by-radius)+'px';+ if(dist<radius){+ // Falloff: full strength at center, easing to 0 at the radius edge+ const pull=(1-dist/radius);+ const tx=dx*strength*pull, ty=dy*strength*pull;+ btn.style.transform=`translate(${tx}px,${ty}px)`;+ lbl.style.transform=`translate(${tx*0.35}px,${ty*0.35}px)`;+ document.getElementById('pull-v').textContent=Math.round(Math.hypot(tx,ty))+'px';+ }else{ reset(); }+ });+ stage.addEventListener('pointerleave',reset);+}else{+ hint.textContent='Tap the button';+}+// Press feedback works on both touch and pointer+btn.addEventListener('pointerdown',()=>btn.classList.add('pressed'));+['pointerup','pointercancel','pointerleave'].forEach(ev=>btn.addEventListener(ev,()=>btn.classList.remove('pressed')));++document.getElementById('str-sl').addEventListener('input',e=>{+ strength=+e.target.value/100;+ document.getElementById('str-v').textContent=strength.toFixed(2);+});+document.getElementById('rad-sl').addEventListener('input',e=>{+ radius=+e.target.value;+ document.getElementById('rad-v').textContent=radius+'px';+ document.documentElement.style.setProperty('--radius',radius);+});+document.getElementById('ring-tog').addEventListener('change',e=>{+ ring.classList.toggle('show',e.target.checked);+});+</script>+</body>+</html>diff --git a/animations/04-micro-interactions/success-confetti/README.md b/animations/04-micro-interactions/success-confetti/README.mdnew file mode 100644index 00000000..f7705757--- /dev/null+++ b/animations/04-micro-interactions/success-confetti/README.md@@ -0,0 +1,66 @@+# Success Confetti++## What it is+A confetti burst that fires when a user completes a meaningful action — placing an order, finishing onboarding, submitting a form. Clicking the button switches it to a success state and launches many small rotating rectangles from the button's position, each with an upward-and-outward velocity, gravity, and spin, that fall and fade. It is a reward animation: it marks completion, it does not convey new information.++## When to use it+- Checkout / "Place order" confirmation, sign-up completion, plan upgrades+- The final step of a multi-step flow, where the payoff justifies the flourish+- Achievement and streak moments in learning or fitness apps+- Once per event, on genuine milestones — confetti on every click trains users to ignore it++## How it works+A `<canvas>` overlay covers the stage. On click you spawn a batch of confetti pieces at the button's center, each fanned around a straight-up base direction by a configurable spread angle. Every frame applies gravity to `vy`, advances position, spins the piece, and drains its life; pieces are retired once faded or off-screen:++```js+function fire() {+ const half = (spreadDeg * Math.PI/180) / 2;+ for (let i = 0; i < pCount; i++) {+ const ang = -Math.PI/2 + (Math.random()*2 - 1) * half; // fan around straight up+ const speed = 6 + Math.random()*7;+ particles.push({ x: ox, y: cy, vx: Math.cos(ang)*speed, vy: Math.sin(ang)*speed,+ w: 6+Math.random()*6, h: 3+Math.random()*5, rot: Math.random()*Math.PI,+ spin: (Math.random()-0.5)*0.3, color: COLORS[i % COLORS.length], life: 1 });+ }+ if (!raf) raf = requestAnimationFrame(tick);+}++function tick() {+ ctx.clearRect(0, 0, cv.width, cv.height);+ particles = particles.filter(p => p.life > 0 && p.y < stage.clientHeight + 40);+ for (const p of particles) {+ p.vy += gravity; p.vx *= 0.99; p.x += p.vx; p.y += p.vy; p.rot += p.spin; p.life -= 0.008;+ ctx.save(); ctx.translate(p.x, p.y); ctx.rotate(p.rot);+ ctx.globalAlpha = p.life; ctx.fillStyle = p.color;+ ctx.fillRect(-p.w/2, -p.h/2, p.w, p.h);+ ctx.restore();+ }+ raf = particles.length ? requestAnimationFrame(tick) : null;+}+```++Because the loop reads live `pCount`, `spreadDeg`, and `gravity` values, adjusting a slider changes the very next burst. Clicking again simply calls `fire()` again — replay is implicit.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Particle count | 120 | Density of the burst. Above ~200 costs frames on low-end phones for little visual gain |+| Spread | 110° | Fan width around vertical. Narrow = a focused fountain; 180° = a full dome |+| Gravity | 0.28 | Downward acceleration per frame. Higher = a snappy, heavy fall; lower = a slow float |+| Fade rate | 0.008/frame | Life drain — sets how long pieces linger (~2s at 60fps) |+| Angular spin | ±0.3 rad/frame | Per-piece rotation speed; the flicker of rectangles catching "light" |++## Production notes+- **Off-screen culling**: filter out pieces once `p.y` passes the stage bottom, not just when faded — otherwise fast-falling confetti keeps consuming CPU below the fold.+- **One rAF, gated**: start the loop on the first burst and stop it when the array empties. Restart on the next click. Never leave a permanent rAF running for an occasional event.+- **DPR-aware canvas**: scale the backing store by `devicePixelRatio` (cap ~2) so rectangles have clean edges on retina without quadrupling fill cost on 3x displays.+- **Rectangles are cheapest**: `fillRect` inside a `translate`/`rotate` beats drawing images or paths per particle. If you need shapes, pre-render sprites to an offscreen canvas once and `drawImage`.+- **Reduced motion**: skip confetti entirely and show a static success state — the checkmark and "Order placed" label already confirm completion. This demo swaps the sub-caption to say so.+- **canvas-confetti**: the go-to library — `confetti({ particleCount: 120, spread: 110, origin: {x, y} })` handles physics, DPR, and cleanup. Reach for hand-rolled code only when you need custom shapes or tight bundle size.+- **GSAP / Framer Motion**: both can animate a handful of DOM confetti for light celebrations, but for hundreds of pieces a single canvas is dramatically cheaper than that many animated nodes.++## See also+- [Checkmark Draw](../checkmark-draw/) — the quieter success confirmation, and the reduced-motion fallback here+- [Button Press Scale](../button-press-scale/) — the press feedback on the trigger button+- [Heart / Like Burst](../heart-burst/) — a smaller, per-tap particle celebration+- [Modal Expand](../modal-expand/) — pairs well as the success dialog confetti fires intodiff --git a/animations/04-micro-interactions/success-confetti/index.html b/animations/04-micro-interactions/success-confetti/index.htmlnew file mode 100644index 00000000..4af1c1fc--- /dev/null+++ b/animations/04-micro-interactions/success-confetti/index.html@@ -0,0 +1,111 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Success Confetti</title>+ <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:'PlexMono';src:url('../../../assets/fonts/plex-400.woff2') format('woff2');font-weight:400;font-display:swap}+ :root{--bg:#0b0b0d;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#ff9d5c;--ui-text:#f4f4f2;--ui-muted:#77777e;--ok:#3fb950;--disp:'Bricolage','Arial Narrow',sans-serif;--mono:'PlexMono',ui-monospace,Menlo,Consolas,monospace;--stage-h:620px}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:var(--mono);-webkit-font-smoothing:antialiased;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-family:var(--disp);font-weight:700;font-size:clamp(16px,2.2vw,22px);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{position:relative;flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;background:var(--bg);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:22px;overflow:hidden;touch-action:manipulation}+ canvas{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}+ .order-btn{position:relative;z-index:2;background:var(--ui-accent);color:#1a0e05;border:none;cursor:pointer;font-family:var(--disp);font-weight:700;font-size:clamp(14px,1.8vw,17px);padding:18px 40px;min-height:56px;border-radius:12px;transition:transform .12s,background .3s;-webkit-tap-highlight-color:transparent}+ .order-btn:active{transform:scale(.96)}+ .order-btn.done{background:var(--ok);color:#04140a}+ .order-btn .check{display:inline-block;margin-right:8px;opacity:0;width:0;transition:opacity .3s}+ .order-btn.done .check{opacity:1;width:auto}+ .sub{font-size:11px;color:var(--ui-muted);z-index:2;text-align:center}+ 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}+ .lbl2{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sval{width:52px;text-align:right;color:var(--ui-text)}+ .kv{display:flex;justify-content:space-between;font-size:10px;color:var(--ui-muted)}+ .kv .v{color:var(--ui-text)}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:auto}.stage{height:auto;min-height:420px}}+ @media(prefers-reduced-motion:reduce){.order-btn:active{transform:none}}+ </style>+</head>+<body>+<header>+ <h1>Success Confetti</h1>+ <p>Completing an action fires a canvas confetti burst — rectangles launched outward with gravity, spin, and fade.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <canvas id="cv"></canvas>+ <button class="order-btn" id="btn"><span class="check">✓</span><span id="btn-lbl">Place order</span></button>+ <div class="sub" id="sub">Click to complete — click again to replay</div>+ </div>+ <aside>+ <p class="note">Each confetto is a rotating rectangle with its own velocity, angular spin, and gravity. They launch upward and outward from the button, then decelerate, fall, and fade — retired once off-screen or faded out.</p>+ <div class="lbl2">Particle Count</div>+ <div class="sr"><input type="range" id="cnt-sl" min="30" max="220" value="120" step="10"><span class="sval" id="cnt-v">120</span></div>+ <div class="lbl2">Spread (deg)</div>+ <div class="sr"><input type="range" id="spr-sl" min="30" max="180" value="110" step="5"><span class="sval" id="spr-v">110°</span></div>+ <div class="lbl2">Gravity</div>+ <div class="sr"><input type="range" id="grv-sl" min="10" max="60" value="28" step="1"><span class="sval" id="grv-v">0.28</span></div>+ <div class="div"></div>+ <div class="kv"><span>Live particles</span><span class="v" id="live-v">0</span></div>+ </aside>+</div>+<script>+const stage=document.getElementById('stage'),btn=document.getElementById('btn'),+ cv=document.getElementById('cv'),ctx=cv.getContext('2d');+const reduce=window.matchMedia('(prefers-reduced-motion: reduce)').matches;+const COLORS=['#ff9d5c','#ff5470','#3fb950','#58a6ff','#ffd166','#c792ea'];+let particles=[],raf=null,dpr=Math.min(window.devicePixelRatio||1,2);+let pCount=120,spreadDeg=110,gravity=0.28;++function resize(){cv.width=stage.clientWidth*dpr;cv.height=stage.clientHeight*dpr;ctx.setTransform(dpr,0,0,dpr,0,0);}+resize();new ResizeObserver(resize).observe(stage);++function fire(){+ const b=btn.getBoundingClientRect(),s=stage.getBoundingClientRect();+ const ox=b.left+b.width/2-s.left; // origin x at button center+ const cy=b.top+b.height/2-s.top; // origin y at button center+ const half=(spreadDeg*Math.PI/180)/2;+ for(let i=0;i<pCount;i++){+ // Base direction is straight up (-90deg), fanned by the spread angle+ const ang=-Math.PI/2+(Math.random()*2-1)*half;+ const speed=6+Math.random()*7;+ particles.push({x:ox,y:cy,vx:Math.cos(ang)*speed,vy:Math.sin(ang)*speed,+ w:6+Math.random()*6,h:3+Math.random()*5,rot:Math.random()*Math.PI,+ spin:(Math.random()-0.5)*0.3,color:COLORS[i%COLORS.length],life:1});+ }+ if(!raf)raf=requestAnimationFrame(tick);+}+function tick(){+ ctx.clearRect(0,0,cv.width,cv.height);+ particles=particles.filter(p=>p.life>0&&p.y<stage.clientHeight+40);+ document.getElementById('live-v').textContent=particles.length;+ for(const p of particles){+ p.vy+=gravity;p.vx*=0.99;p.x+=p.vx;p.y+=p.vy;p.rot+=p.spin;p.life-=0.008;+ ctx.save();ctx.translate(p.x,p.y);ctx.rotate(p.rot);+ ctx.globalAlpha=Math.max(p.life,0);ctx.fillStyle=p.color;+ ctx.fillRect(-p.w/2,-p.h/2,p.w,p.h);ctx.restore();+ }+ ctx.globalAlpha=1;+ if(particles.length)raf=requestAnimationFrame(tick);else raf=null;+}+btn.addEventListener('click',()=>{+ btn.classList.add('done');+ document.getElementById('btn-lbl').textContent='Order placed';+ document.getElementById('sub').textContent=reduce?'Completed — confetti disabled by reduced-motion':'Click again to replay';+ if(!reduce)fire();+});+document.getElementById('cnt-sl').addEventListener('input',e=>{pCount=+e.target.value;document.getElementById('cnt-v').textContent=pCount;});+document.getElementById('spr-sl').addEventListener('input',e=>{spreadDeg=+e.target.value;document.getElementById('spr-v').textContent=spreadDeg+'°';});+document.getElementById('grv-sl').addEventListener('input',e=>{gravity=+e.target.value/100;document.getElementById('grv-v').textContent=gravity.toFixed(2);});+</script>+</body>+</html>diff --git a/animations/04-micro-interactions/swipe-to-dismiss/README.md b/animations/04-micro-interactions/swipe-to-dismiss/README.mdnew file mode 100644index 00000000..dce20115--- /dev/null+++ b/animations/04-micro-interactions/swipe-to-dismiss/README.md@@ -0,0 +1,56 @@+# Swipe to Dismiss++## What it is+Swipe to dismiss lets a user drag a list item horizontally and, past a distance or velocity threshold, throw it off-screen to remove it. While dragging, the card tracks the finger 1:1; on release it either flies off and its row collapses to zero height, or springs back to rest. It is the interaction behind swipe-to-delete in mail and message apps.++## When to use it+- Mail, chat, and notification lists where "delete" or "archive" is the dominant action+- Card feeds where items are transient (dismissable tips, cleared alerts)+- Any touch-first list where a per-row button would be cramped or slow+- Undo-friendly destructive actions — pair the fly-off with a "Undo" snackbar++## How it works+Each card is dragged with **Pointer Events** so one code path covers mouse, touch, and pen. `pointerdown` captures the pointer and records the start X; `pointermove` sets `translateX` to the delta and fades opacity with distance; `pointerup` decides the outcome:++```js+card.addEventListener('pointermove', e => {+ if (!dragging) return;+ dx = e.clientX - startX;+ const now = performance.now();+ if (now > lastT){ vel = (e.clientX - lastX)/(now - lastT); lastX = e.clientX; lastT = now; }+ card.style.transform = `translateX(${dx}px)`;+ card.style.opacity = String(Math.max(0.3, 1 - Math.abs(dx)/(card.offsetWidth*0.9)));+});++function end(){+ const w = card.offsetWidth;+ const pastDist = Math.abs(dx) > w * threshold; // committed by distance+ const flick = Math.abs(vel) > 0.6 && Math.abs(dx) > 24; // or by velocity+ (pastDist || flick) ? dismiss(row, card, dx >= 0 ? 1 : -1) : spring(card, reveal);+}+```++Commit is decided by distance **or** velocity — a fast flick counts even if the finger didn't travel far, which is what makes the gesture feel responsive. On dismiss, the card gets a `flung` transition to slide fully off-screen while the wrapping `.row` animates its `height` to `0`, collapsing the gap so the list closes up. `touch-action: pan-y` on the card lets vertical page scroll pass through while the horizontal drag is claimed by JS.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Dismiss threshold | 35% | Fraction of card width the drag must pass to commit on release |+| Velocity threshold | 0.6 px/ms | A flick above this commits even below the distance threshold |+| Fly-off distance | 125% width | How far past the edge the card slides before the row collapses |+| Collapse duration | 280ms | Row height `→ 0` timing; sets how fast the list closes the gap |+| Reveal background | on | Red "Delete" action shown behind the card while dragging |++## Production notes+- **Use `setPointerCapture`** so `pointermove`/`pointerup` keep firing even if the finger leaves the card's box mid-drag; without it a fast swipe can drop events.+- **`touch-action`** is essential: set `pan-y` (or `none` if you also handle vertical) on the draggable element, otherwise the browser's native scroll fights your drag and the gesture stutters on mobile.+- **Collapse the row, not the card.** Animate the height of an outer wrapper to `0`; animating the card's own height while it's mid-fling causes reflow jank. Keep transforms/opacity on the card, layout collapse on the row.+- **Reduced motion**: keep the *functionality* but drop the easing flourish — on `prefers-reduced-motion: reduce`, remove the fly-off transition and collapse the row instantly so nothing slides.+- **Always offer undo** for destructive swipes; a fly-off with no recovery path punishes fat-fingers. Remove from the DOM only after the undo window closes.+- **Library equivalents**: Framer Motion's `drag="x"` with `dragConstraints`, `onDragEnd`, and an `AnimatePresence` exit handles this declaratively; `react-swipeable` exposes `onSwipedLeft`/velocity handlers if you want gesture callbacks without the transform plumbing; SortableJS covers the reorder cousin of this gesture; GSAP's `Draggable` with `throwProps`/inertia gives physics-based fling and snap-back.++## See also+- [Drawer Slide](../drawer-slide/) — another off-screen translate driven by a gesture+- [Modal Expand](../modal-expand/) — enter/exit transition for the detail view a swipe might open+- [Button Press Scale](../button-press-scale/) — tactile press feedback for the row's tap target+- [Toggle / Switch Slide](../toggle-switch/) — a smaller drag-and-settle horizontal controldiff --git a/animations/04-micro-interactions/swipe-to-dismiss/index.html b/animations/04-micro-interactions/swipe-to-dismiss/index.htmlnew file mode 100644index 00000000..14f0e11c--- /dev/null+++ b/animations/04-micro-interactions/swipe-to-dismiss/index.html@@ -0,0 +1,167 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Swipe to Dismiss</title>+ <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}+ @font-face{font-family:'PlexMono';src:url('../../../assets/fonts/plex-400.woff2') format('woff2');font-weight:400;font-display:swap}+ @font-face{font-family:'PlexMono';src:url('../../../assets/fonts/plex-500.woff2') format('woff2');font-weight:500;font-display:swap}+ :root{--bg:#0b0b0d;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#ff9d5c;--ui-text:#f4f4f2;--ui-muted:#77777e;--disp:'Bricolage','Arial Narrow',sans-serif;--mono:'PlexMono',ui-monospace,Menlo,Consolas,monospace;--stage-h:620px;--del:#f4515b}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:var(--mono);-webkit-font-smoothing:antialiased;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ 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;background:var(--bg);display:flex;align-items:center;justify-content:center;padding:clamp(16px,4vw,32px);overflow:hidden}+ .list{width:100%;max-width:340px;display:flex;flex-direction:column;gap:8px}+ /* Row wrapper collapses its own height when the card is dismissed */+ .row{position:relative;height:66px;transition:height .28s cubic-bezier(.4,0,.2,1),opacity .2s;overflow:hidden}+ .row.collapsing{height:0!important;opacity:0}+ /* Reveal action sits behind the card */+ .reveal{position:absolute;inset:0;border-radius:10px;background:var(--del);display:flex;align-items:center;justify-content:flex-end;padding:0 20px;font-family:var(--disp);font-weight:700;font-size:12px;color:#fff;opacity:0;transition:opacity .12s}+ .reveal.show{opacity:1}+ .reveal.hidden{display:none}+ /* The draggable card */+ .card{position:absolute;inset:0;border-radius:10px;background:var(--ui-bg);border:1px solid var(--ui-border);display:flex;align-items:center;gap:12px;padding:0 16px;cursor:grab;touch-action:pan-y;-webkit-user-select:none;user-select:none;will-change:transform}+ .card.settling{transition:transform .32s cubic-bezier(.22,1,.36,1),opacity .32s}+ .card.flung{transition:transform .3s cubic-bezier(.4,0,1,1),opacity .3s}+ .avatar{width:36px;height:36px;border-radius:50%;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-family:var(--disp);font-weight:700;font-size:14px;color:#1a0f08;background:var(--ui-accent)}+ .meta{min-width:0}+ .meta .t{font-size:12px;color:var(--ui-text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+ .meta .s{font-size:10px;color:var(--ui-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+ .empty{font-size:11px;color:var(--ui-muted);text-align:center}+ 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)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sval{width:44px;text-align:right;color:var(--ui-text)}+ .tog-inp{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}+ .tog-inp input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}+ .div{height:1px;background:var(--ui-border)}+ .reset{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){.reset:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:auto}.stage{height:auto;min-height:420px}}+ @media(prefers-reduced-motion:reduce){.row,.card.settling,.card.flung{transition:none!important}}+ </style>+</head>+<body>+<header>+ <h1>Swipe to Dismiss</h1>+ <p>Drag a card past the threshold (or fling it) to delete; release short and it springs back.</p>+</header>+<div class="layout">+ <div class="stage">+ <div class="list" id="list"></div>+ </div>+ <aside>+ <p class="note">The card follows your finger 1:1 while dragging. Commit is decided at release by distance OR velocity — a fast flick counts even if it's short.</p>+ <div class="lbl">Dismiss threshold</div>+ <div class="sr"><input type="range" id="th-sl" min="15" max="70" value="35" step="5"><span class="sval" id="th-v">35%</span></div>+ <label class="tog-inp"><input type="checkbox" id="reveal-tog" checked><span>Show delete background</span></label>+ <div class="div"></div>+ <button class="reset" id="reset">↺ Reset list</button>+ </aside>+</div>+<script>+ const listEl=document.getElementById('list');+ const root=document.documentElement.style;+ let threshold=0.35, showReveal=true;+ const reduce=window.matchMedia('(prefers-reduced-motion:reduce)').matches;+ const DATA=[+ ['AV','Ava Reyes','Lunch tomorrow? I found a spot'],+ ['KM','Kai Morgan','Deploy is green, shipping it'],+ ['NP','Noor Patel','Sent the revised mockups'],+ ['TG','Theo Grant','Re: invoice — all sorted'],+ ['SL','Sol Lindqvist','Are we still on for Friday?']+ ];++ function build(){+ listEl.innerHTML='';+ DATA.forEach(d=>{+ const row=document.createElement('div');row.className='row';+ row.innerHTML=`<div class="reveal ${showReveal?'':'hidden'}">Delete</div>`++ `<div class="card"><div class="avatar">${d[0]}</div>`++ `<div class="meta"><div class="t">${d[1]}</div><div class="s">${d[2]}</div></div></div>`;+ listEl.appendChild(row);+ wire(row);+ });+ }++ function wire(row){+ const card=row.querySelector('.card');+ const reveal=row.querySelector('.reveal');+ let startX=0,dx=0,dragging=false,lastX=0,lastT=0,vel=0;++ card.addEventListener('pointerdown',e=>{+ dragging=true;dx=0;startX=e.clientX;lastX=e.clientX;lastT=e.now||performance.now();vel=0;+ card.classList.remove('settling','flung');+ card.setPointerCapture(e.pointerId);+ card.style.cursor='grabbing';+ });+ card.addEventListener('pointermove',e=>{+ if(!dragging)return;+ dx=e.clientX-startX;+ const now=performance.now();+ if(now>lastT){vel=(e.clientX-lastX)/(now-lastT);lastX=e.clientX;lastT=now;} // px per ms+ card.style.transform=`translateX(${dx}px)`;+ card.style.opacity=String(Math.max(0.3,1-Math.abs(dx)/(card.offsetWidth*0.9)));+ if(reveal)reveal.classList.toggle('show',showReveal&&Math.abs(dx)>8);+ });+ function end(){+ if(!dragging)return;dragging=false;card.style.cursor='grab';+ const w=card.offsetWidth;+ const pastDist=Math.abs(dx)>w*threshold;+ const flick=Math.abs(vel)>0.6&&Math.abs(dx)>24; // velocity commit+ if(pastDist||flick){dismiss(row,card,dx>=0?1:-1);}+ else{spring(card,reveal);}+ }+ card.addEventListener('pointerup',end);+ card.addEventListener('pointercancel',end);+ }++ function spring(card,reveal){+ card.classList.add('settling');+ card.style.transform='translateX(0)';+ card.style.opacity='1';+ if(reveal)reveal.classList.remove('show');+ }++ function dismiss(row,card,dir){+ if(reduce){ // no fly-off flourish — collapse immediately+ row.style.height='0';row.style.opacity='0';+ setTimeout(()=>row.remove(),0);checkEmpty();return;+ }+ card.classList.add('flung');+ card.style.transform=`translateX(${dir*card.offsetWidth*1.25}px)`;+ card.style.opacity='0';+ row.classList.add('collapsing');+ row.addEventListener('transitionend',function te(ev){+ if(ev.propertyName==='height'){row.remove();checkEmpty();}+ });+ }++ function checkEmpty(){+ if(!listEl.querySelector('.row')){+ listEl.innerHTML='<div class="empty">All cleared. Reset the list to try again.</div>';+ }+ }++ document.getElementById('th-sl').addEventListener('input',e=>{+ threshold=+e.target.value/100;+ document.getElementById('th-v').textContent=e.target.value+'%';+ });+ document.getElementById('reveal-tog').addEventListener('change',e=>{+ showReveal=e.target.checked;+ document.querySelectorAll('.reveal').forEach(r=>r.classList.toggle('hidden',!showReveal));+ });+ document.getElementById('reset').addEventListener('click',build);++ build();+</script>+</body>+</html>diff --git a/animations/05-text-typography/README.md b/animations/05-text-typography/README.mdindex ae09e7b8..55ef144e 100644--- a/animations/05-text-typography/README.md+++ b/animations/05-text-typography/README.md@@ -17,6 +17,9 @@ Animations specifically for type — where the letterforms themselves are the co| [Outline to Fill](outline-to-fill/) | Hollow stroke letterforms fill with color via clip-path or opacity crossfade || [Enter/Exit Typography](enter-exit-typography/) | Three-act phrase lifecycle: enter → hold → exit, sequenced for storytelling || [Rotate Word Carousel](rotate-word-carousel/) | One keyword cycles through a list while the surrounding sentence stays static |+| [Glitch Text](glitch-text/) | RGB-split copies jitter behind animated clip-path slices — the datamosh / signal-loss look |+| [Text on a Path](text-on-path/) | Text flows along an SVG curve via textPath with an animated startOffset |+| [Wavy Text](wavy-text/) | Per-letter sine-wave bob with a staggered delay sends a wave travelling across the word |## Key principlesdiff --git a/animations/05-text-typography/glitch-text/README.md b/animations/05-text-typography/glitch-text/README.mdnew file mode 100644index 00000000..690e6585--- /dev/null+++ b/animations/05-text-typography/glitch-text/README.md@@ -0,0 +1,48 @@+# Glitch Text++## What it is+Glitch text simulates a corrupted video signal on a headline. A white base layer sits between a red-shifted copy and a cyan-shifted copy, and horizontal `clip-path` bands slice each copy so ragged strips of color tear away from the letters. The effect reads as digital malfunction — datamosh, VHS dropout, a signal losing sync.++## When to use it+- Hero headlines for cyberpunk, hacker, or music/streetwear brands+- Error and 404 states where a "broken signal" metaphor fits the tone+- Hover accents on nav or buttons for a brief burst of instability+- Loading or transition moments that want texture rather than a plain spinner++## How it works+The visible text is duplicated twice with `content: attr(data-text)` on `::before` and `::after`. Each clone is nudged sideways and tinted a single channel, then a `clip-path: inset(...)` keyframe reveals a different horizontal band on every step. The `inset()` top/bottom values jump around, so the color layers only show through in shifting strips:++```css+.glitch::before{+ color:#ff2d5e;+ left:calc(var(--offset)*-1);+ animation:slice var(--speed) infinite linear alternate-reverse;+}+@keyframes slice{+ 0%{clip-path:inset(20% 0 60% 0)}+ 40%{clip-path:inset(10% 0 80% 0)}+ 80%{clip-path:inset(85% 0 2% 0)}+ 100%{clip-path:inset(30% 0 55% 0)}+}+```++A small JS loop re-triggers the animation and nudges the element's `translateX` at irregular intervals, so the tear never settles into an obvious loop. Hover-trigger mode simply toggles `animation-play-state` via a `:hover` rule gated behind `@media (hover: hover)`.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| RGB offset | 4px | Horizontal gap between the red and cyan copies — larger = more separation |+| Speed | 2.4s | Cycle duration of the `clip-path` keyframes; shorter = more frantic |+| Intensity | 60% | Probability and amplitude of the JS jitter re-triggers |+| Trigger | continuous | `continuous` runs always; `hover-trigger` pauses until pointer enters |++## Production notes+- **Accessibility**: the glitch is one element with real text content, so it stays selectable and readable to screen readers. When you build the effect from split spans instead, add `aria-label` on the container and `aria-hidden="true"` on the fragments so assistive tech reads the word once.+- **Reduced motion**: the demo disables the slice animation and the JS jitter under `@media (prefers-reduced-motion: reduce)`, leaving a static RGB split — still on-brand, no flashing.+- **Seizure safety**: keep the jitter below a few hertz and avoid full-frame flashes. Rapid, high-contrast strobing can trigger photosensitive reactions.+- **Library equivalents**: GSAP's timeline with random `clip-path` tweens gives frame-precise control; Splitting.js can shard the text for per-character glitching. Framer Motion can drive the offsets via `useAnimationFrame`.++## See also+- [Scramble Text](../scramble-text/) — another "signal corruption" text treatment+- [Text Clip-Path Reveal](../text-clip-path-reveal/) — clip-path used to reveal rather than tear+- [Kinetic Typography](../kinetic-typography/) — broader motion-driven type patternsdiff --git a/animations/05-text-typography/glitch-text/index.html b/animations/05-text-typography/glitch-text/index.htmlnew file mode 100644index 00000000..9da28a0f--- /dev/null+++ b/animations/05-text-typography/glitch-text/index.html@@ -0,0 +1,138 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Glitch Text</title>+ <style>+ :root{+ --bg:#0b0b0d;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#ff6f8b;+ --ui-text:#f4f4f2;--ui-muted:#77777e;+ --disp:'Arial Narrow','Segoe UI',system-ui,sans-serif;--mono:ui-monospace,Menlo,Consolas,monospace;+ --stage-h:520px;--offset:4px;--speed:2.4s;+ }+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:var(--mono);-webkit-font-smoothing:antialiased;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-family:var(--disp);font-weight:800;font-size:clamp(16px,2.2vw,22px);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;+ background:radial-gradient(circle at 50% 40%,#141018,#04060c);display:flex;align-items:center;justify-content:center;padding:24px;overflow:hidden}+ /* Glitch text: three stacked copies via ::before/::after clones */+ .glitch{+ position:relative;font-family:var(--disp);font-weight:800;+ font-size:clamp(44px,12vw,120px);line-height:1;letter-spacing:-.02em;color:#fff;+ text-transform:uppercase;-webkit-user-select:none;user-select:none;+ }+ .glitch::before,.glitch::after{+ content:attr(data-text);position:absolute;inset:0;+ clip-path:inset(0 0 0 0);+ }+ .glitch::before{color:#ff2d5e;text-shadow:calc(var(--offset)*-1) 0 #ff2d5e;left:calc(var(--offset)*-1);+ animation:slice var(--speed) infinite linear alternate-reverse}+ .glitch::after{color:#2dffe6;text-shadow:var(--offset) 0 #2dffe6;left:var(--offset);+ animation:slice2 var(--speed) infinite linear alternate-reverse}+ /* clip-path slices are re-randomized from JS via --a../--b.. custom props */+ @keyframes slice{+ 0%{clip-path:inset(20% 0 60% 0)}20%{clip-path:inset(70% 0 5% 0)}+ 40%{clip-path:inset(10% 0 80% 0)}60%{clip-path:inset(45% 0 35% 0)}+ 80%{clip-path:inset(85% 0 2% 0)}100%{clip-path:inset(30% 0 55% 0)}+ }+ @keyframes slice2{+ 0%{clip-path:inset(65% 0 10% 0)}20%{clip-path:inset(15% 0 70% 0)}+ 40%{clip-path:inset(80% 0 8% 0)}60%{clip-path:inset(30% 0 45% 0)}+ 80%{clip-path:inset(5% 0 85% 0)}100%{clip-path:inset(50% 0 30% 0)}+ }+ /* hover-trigger mode: layers hold still until pointer enters */+ .paused .glitch::before,.paused .glitch::after{animation-play-state:paused}+ @media(hover:hover){.paused:hover .glitch::before,.paused:hover .glitch::after{animation-play-state:running}}+ 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)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:44px;text-align:right;color:var(--ui-text)}+ input[type=text]{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:var(--mono);font-size:11px;padding:8px 10px;border-radius:4px;width:100%;min-height:44px;outline:none}+ input[type=text]:focus{border-color:var(--ui-accent)}+ .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}+ .div{height:1px;background:var(--ui-border)}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:auto}.stage{height:auto;min-height:360px}}+ @media(prefers-reduced-motion:reduce){+ .glitch::before,.glitch::after{animation:none!important;clip-path:none!important}+ }+ </style>+</head>+<body>+<header>+ <h1>Glitch Text</h1>+ <p>Two color-split copies of a headline are sliced by animated clip-path bands that jump on a jittery timeline.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <div class="glitch" id="glitch" data-text="GLITCH">GLITCH</div>+ </div>+ <aside>+ <p class="note">RGB-split: a red and a cyan clone sit behind the white text, offset sideways. Horizontal clip-path slices reveal random bands, and re-randomizing them each cycle makes the tear look non-repeating.</p>+ <div class="lbl">Text</div>+ <input type="text" id="text-inp" value="GLITCH" maxlength="12">+ <div class="lbl">RGB offset</div>+ <div class="sr"><input type="range" id="off-sl" min="0" max="12" value="4" step="1"><span class="sv" id="off-sv">4px</span></div>+ <div class="lbl">Speed</div>+ <div class="sr"><input type="range" id="spd-sl" min="1" max="12" value="6" step="1"><span class="sv" id="spd-sv">2.4s</span></div>+ <div class="lbl">Intensity</div>+ <div class="sr"><input type="range" id="int-sl" min="0" max="100" value="60" step="5"><span class="sv" id="int-sv">60%</span></div>+ <div class="div"></div>+ <label class="tog"><input type="checkbox" id="hover-ck"> Hover-trigger only</label>+ </aside>+</div>+<script>+const glitch=document.getElementById('glitch');+const stage=document.getElementById('stage');+const root=document.documentElement;+const reduce=matchMedia('(prefers-reduced-motion:reduce)').matches;+let intensity=0.6,jitterTimer=null;++// Re-randomize the clip-path keyframes so each burst of slices differs.+function rand(max){return Math.floor(Math.random()*max)}+function reslice(){+ if(reduce)return;+ // amplitude of the tear scales with intensity: low intensity = thin, rare bands+ const spread=Math.round(intensity*40);+ const jitter=(intensity*6).toFixed(1);+ glitch.style.setProperty('--offset',(parseInt(root.style.getPropertyValue('--offset'))||4)+'px');+ // nudge the whole element sideways for a frame to sell the tear+ glitch.style.transform=`translateX(${(Math.random()*2-1)*jitter}px)`;+ // occasionally hard-cut a fresh clip band on the ::before via inline var not possible;+ // instead we retrigger animation to reshuffle phase+ if(Math.random()<intensity){+ glitch.style.animation='none';void glitch.offsetWidth;glitch.style.animation='';+ }+ jitterTimer=setTimeout(reslice,120+rand(spread*8+60));+}++document.getElementById('text-inp').addEventListener('input',e=>{+ const t=(e.target.value||'GLITCH');glitch.textContent=t;glitch.dataset.text=t;+});+document.getElementById('off-sl').addEventListener('input',e=>{+ root.style.setProperty('--offset',e.target.value+'px');+ document.getElementById('off-sv').textContent=e.target.value+'px';+});+document.getElementById('spd-sl').addEventListener('input',e=>{+ // higher slider = faster = shorter duration (invert)+ const dur=(14-+e.target.value)*0.4;+ root.style.setProperty('--speed',dur.toFixed(1)+'s');+ document.getElementById('spd-sv').textContent=dur.toFixed(1)+'s';+});+document.getElementById('int-sl').addEventListener('input',e=>{+ intensity=+e.target.value/100;+ document.getElementById('int-sv').textContent=e.target.value+'%';+});+document.getElementById('hover-ck').addEventListener('change',e=>{+ stage.classList.toggle('paused',e.target.checked);+});+if(!reduce)reslice();+</script>+</body>+</html>diff --git a/animations/05-text-typography/text-on-path/README.md b/animations/05-text-typography/text-on-path/README.mdnew file mode 100644index 00000000..166a91ef--- /dev/null+++ b/animations/05-text-typography/text-on-path/README.md@@ -0,0 +1,49 @@+# Text on a Path++## What it is+Text on a path lets a string of type follow an arbitrary curve instead of a straight baseline. In SVG this is done with `<textPath>`, which binds a `<text>` element to a `<path>`. Animating the `startOffset` attribute slides the string along that path, so the letters appear to travel down the curve like a ticker bent into a shape.++## When to use it+- Circular badges, seals, and stamps where text wraps a ring+- Decorative headlines that arc, wave, or spiral across a hero+- Diagrams and infographics where a label should hug a route or connector+- Looping marquees that follow a shape rather than a flat line++## How it works+The path is declared once inside `<defs>` with an `id`. A `<textPath href="#curve">` references it, and the glyphs lay themselves along the curve automatically. Each animation frame advances `startOffset` by a small percentage, wrapping at 100%:++```html+<defs><path id="curve" d="M20,180 C120,60 240,300 340,180 S560,60 620,180"/></defs>+<text class="flow-text">+ <textPath href="#curve" id="tp" startOffset="0%">FOLLOW THE CURVE · </textPath>+</text>+```++```js+function loop(){+ offset=(offset+speed)%100;+ tp.setAttribute('startOffset',offset+'%');+ requestAnimationFrame(loop);+}+```++Switching path shape swaps the `d` attribute on the same `<path>` — the text re-flows onto the new geometry with no other changes. The dashed guide is a `<use href="#curve">` of the identical path, toggled by opacity.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Speed | 0.4%/frame | How far `startOffset` advances each frame; higher = faster scroll |+| Path shape | wave | The `d` geometry: wave (cubic), arc (quadratic), or circle (elliptical arc) |+| Show guide | on | Renders the underlying path as a dashed stroke for reference |+| Text | user string | Append a separator (` · `) so the loop reads continuously when it wraps |++## Production notes+- **Accessibility**: SVG text stays real, selectable text and is read in DOM order — add `aria-label` on the `<svg>` describing the phrase, since the animated offset can split a word visually at the wrap point.+- **Legibility on tight curves**: sharp turns crowd or fan the glyphs. Reduce `letter-spacing`, shorten the string, or ease the curvature. `textPath` has no automatic kerning correction around corners.+- **Reduced motion**: gate the `requestAnimationFrame` loop behind a `prefers-reduced-motion` check and render the text at a fixed `startOffset` so it stays legible without scrolling.+- **Library equivalents**: GSAP's MotionPathPlugin animates elements (not just text) along a path with autorotation; D3 exposes `path` generators handy for data-driven curves. For circular type specifically, CSS `writing-mode` tricks exist but `<textPath>` remains the most flexible.++## See also+- [Marquee / Ticker](../marquee-ticker/) — the straight-line cousin of path-scrolled text+- [Kinetic Typography](../kinetic-typography/) — motion-driven type layouts+- [Text Morphing](../text-morphing/) — animating between letterforms rather than along a pathdiff --git a/animations/05-text-typography/text-on-path/index.html b/animations/05-text-typography/text-on-path/index.htmlnew file mode 100644index 00000000..56939d86--- /dev/null+++ b/animations/05-text-typography/text-on-path/index.html@@ -0,0 +1,116 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Text on a Path</title>+ <style>+ :root{+ --bg:#0b0b0d;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#ff6f8b;+ --ui-text:#f4f4f2;--ui-muted:#77777e;+ --disp:'Arial Narrow','Segoe UI',system-ui,sans-serif;--mono:ui-monospace,Menlo,Consolas,monospace;+ --stage-h:520px;+ }+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:var(--mono);-webkit-font-smoothing:antialiased;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-family:var(--disp);font-weight:800;font-size:clamp(16px,2.2vw,22px);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;+ background:radial-gradient(circle at 50% 45%,#101018,#04060c);display:flex;align-items:center;justify-content:center;padding:16px;overflow:hidden}+ svg{width:100%;height:100%;max-width:640px}+ .flow-text{font-family:var(--disp);font-weight:800;font-size:34px;letter-spacing:2px;fill:var(--ui-text)}+ .guide{fill:none;stroke:var(--ui-accent);stroke-width:1.5;stroke-dasharray:5 6;opacity:.5;transition:opacity .2s}+ .guide.hidden{opacity:0}+ 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)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:44px;text-align:right;color:var(--ui-text)}+ input[type=text]{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:var(--mono);font-size:11px;padding:8px 10px;border-radius:4px;width:100%;min-height:44px;outline:none}+ input[type=text]:focus{border-color:var(--ui-accent)}+ .seg{display:flex;gap:6px}+ .seg button{flex:1;background:none;border:1px solid var(--ui-border);color:var(--ui-muted);font-family:var(--mono);font-size:10px;padding:6px;border-radius:4px;cursor:pointer;min-height:44px}+ .seg button.on{border-color:var(--ui-accent);color:var(--ui-accent)}+ @media(hover:hover){.seg button:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ .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}+ .div{height:1px;background:var(--ui-border)}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:auto}.stage{height:auto;min-height:340px}}+ </style>+</head>+<body>+<header>+ <h1>Text on a Path</h1>+ <p>An SVG textPath binds a string to a curve, and animating startOffset scrolls the text along it.</p>+</header>+<div class="layout">+ <div class="stage">+ <svg viewBox="0 0 640 360" xmlns="http://www.w3.org/2000/svg" aria-label="animated text following a curved path">+ <defs>+ <path id="curve" d="M20,180 C120,60 240,300 340,180 S560,60 620,180"/>+ </defs>+ <use href="#curve" class="guide" id="guide"/>+ <text class="flow-text">+ <textPath href="#curve" id="tp" startOffset="0%">FOLLOW THE CURVE · </textPath>+ </text>+ </svg>+ </div>+ <aside>+ <p class="note">The path is defined once in defs. textPath lays glyphs along it, and each frame we advance startOffset so the string appears to travel down the curve.</p>+ <div class="lbl">Text</div>+ <input type="text" id="text-inp" value="FOLLOW THE CURVE · " maxlength="40">+ <div class="lbl">Path shape</div>+ <div class="seg" id="shape">+ <button data-shape="wave" class="on">Wave</button>+ <button data-shape="arc">Arc</button>+ <button data-shape="circle">Circle</button>+ </div>+ <div class="lbl">Speed</div>+ <div class="sr"><input type="range" id="spd-sl" min="0" max="100" value="40" step="5"><span class="sv" id="spd-sv">40</span></div>+ <div class="div"></div>+ <label class="tog"><input type="checkbox" id="guide-ck" checked> Show guide path</label>+ </aside>+</div>+<script>+const tp=document.getElementById('tp');+const curve=document.getElementById('curve');+const guide=document.getElementById('guide');+const reduce=matchMedia('(prefers-reduced-motion:reduce)').matches;+const PATHS={+ wave:'M20,180 C120,60 240,300 340,180 S560,60 620,180',+ arc:'M20,300 Q320,20 620,300',+ circle:'M320,60 a120,120 0 1,1 -0.1,0'+};+let offset=0,speed=0.4,raf=null;++function loop(){+ offset=(offset+speed)%100;+ tp.setAttribute('startOffset',offset+'%');+ raf=requestAnimationFrame(loop);+}+function start(){ if(reduce||raf)return; raf=requestAnimationFrame(loop); }++document.getElementById('text-inp').addEventListener('input',e=>{+ tp.textContent=e.target.value||' ';+});+document.getElementById('spd-sl').addEventListener('input',e=>{+ speed=+e.target.value/100;+ document.getElementById('spd-sv').textContent=e.target.value;+});+document.getElementById('guide-ck').addEventListener('change',e=>{+ guide.classList.toggle('hidden',!e.target.checked);+});+document.querySelectorAll('#shape button').forEach(b=>{+ b.addEventListener('click',()=>{+ document.querySelectorAll('#shape button').forEach(x=>x.classList.remove('on'));+ b.classList.add('on');+ curve.setAttribute('d',PATHS[b.dataset.shape]);+ });+});+start();+</script>+</body>+</html>diff --git a/animations/05-text-typography/variable-font-morph/README.md b/animations/05-text-typography/variable-font-morph/README.mdindex 9eeab712..3f56a284 100644--- a/animations/05-text-typography/variable-font-morph/README.md+++ b/animations/05-text-typography/variable-font-morph/README.md@@ -68,7 +68,7 @@ setInterval(() => { apply(...Object.values(PRESETS[i++ % PRESETS.length])); }, 1- **`font-variation-settings` is all-or-nothing**: if you set `font-variation-settings: 'wght' 700`, all other axes reset to their defaults. Always specify all axes you care about, even if unchanged.- **CSS `font-weight` is preferred for weight**: `font-weight: 700` works with variable fonts and is more readable than `font-variation-settings: 'wght' 700`. Use `font-variation-settings` only for non-standard axes (`CASL`, `MONO`, etc.).- **Transition performance**: variable font interpolation is handled by the GPU text rendering pipeline in modern browsers. It is not as fast as `transform`/`opacity` animations, but it is generally smooth on mid-range devices for single display elements.-- **Font loading**: this demo uses Google Fonts CDN (one external request). In production, self-host the variable font file and use `@font-face` with `font-display: swap` to avoid layout shift.+- **Font loading**: this demo ships no font files — it targets `system-ui`, which resolves to a real variable font on modern OSes (Segoe UI Variable on Windows 11, San Francisco on macOS), so the `wght` axis morphs smoothly offline. `font-weight` and a `skewX()` transform are wired as universal fallbacks so weight and slant still animate where no variable font is present. In production, self-host a variable font (e.g. Recursive) via `@font-face` with `font-display: swap` to unlock font-specific axes like `CASL`.- **Recommended variable fonts**: Recursive (CASL, MONO, slnt, wght), Inter (wght), Fraunces (opsz, SOFT, WONK, wght), Bricolage Grotesque (opsz, wdth, wght).## See alsodiff --git a/animations/05-text-typography/variable-font-morph/index.html b/animations/05-text-typography/variable-font-morph/index.htmlindex 9ab4223a..0b3592f4 100644--- a/animations/05-text-typography/variable-font-morph/index.html+++ b/animations/05-text-typography/variable-font-morph/index.html@@ -4,8 +4,6 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Variable Font Morph</title>- <link rel="preconnect" href="https://fonts.googleapis.com">- <link href="https://fonts.googleapis.com/css2?family=Recursive:[email protected]&display=swap" rel="stylesheet"><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}@@ -21,16 +19,20 @@.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:24px;padding:32px}.vf-label{font-size:10px;letter-spacing:3px;text-transform:uppercase;color:var(--ui-muted)}.vf-text{- font-family:'Recursive',Georgia,serif;+ font-family:'Recursive','Segoe UI Variable',system-ui,'Segoe UI',sans-serif;font-size:clamp(56px,10vw,110px);line-height:1;color:#fff;letter-spacing:-0.02em;+ /* wght/slnt are standard axes system-ui exposes; font-weight + skewX are the+ universal fallback so the morph is visible even without a variable font. */+ font-weight:var(--wght);font-variation-settings:'wght' var(--wght),'CASL' var(--CASL),'slnt' var(--slnt);- transition:font-variation-settings 600ms cubic-bezier(.4,0,.2,1);+ transform:skewX(calc(var(--slnt) * -1deg));+ transition:font-variation-settings 600ms cubic-bezier(.4,0,.2,1),font-weight 600ms cubic-bezier(.4,0,.2,1),transform 600ms cubic-bezier(.4,0,.2,1);-webkit-user-select:none;user-select:none}- .vf-sub{font-family:'Recursive',monospace;font-size:clamp(13px,2vw,18px);color:var(--ui-muted);letter-spacing:0.1em;font-variation-settings:'wght' 300,'CASL' 0,'slnt' 0}+ .vf-sub{font-family:'Recursive','Segoe UI Variable',system-ui,monospace;font-size:clamp(13px,2vw,18px);color:var(--ui-muted);letter-spacing:0.1em;font-weight:300}/* Axis readout */.axis-row{display:flex;gap:20px;font-size:10px;color:var(--ui-muted)}.axis-val{color:var(--ui-accent)}@@ -67,7 +69,7 @@<div class="stage"><div class="vf-label">Variable</div><div class="vf-text" id="vf-text">Type</div>- <div class="vf-sub" id="vf-sub">Recursive · wght + CASL + slnt</div>+ <div class="vf-sub" id="vf-sub">system-ui · wght + slnt (CASL needs a font that exposes it)</div><div class="axis-row"><span>wght: <span class="axis-val" id="wght-v">400</span></span><span>casual: <span class="axis-val" id="casl-v">0.0</span></span>@@ -94,7 +96,7 @@<div class="lbl">Text</div><input type="text" id="text-inp" value="Type"><button class="rst" id="auto-btn">▶ Auto-morph presets</button>- <div class="kv"><span>Font</span><span class="v">Recursive</span></div>+ <div class="kv"><span>Font</span><span class="v">system-ui</span></div><div class="kv"><span>Axes</span><span class="v">wght · CASL · slnt</span></div></aside></div>diff --git a/animations/05-text-typography/wavy-text/README.md b/animations/05-text-typography/wavy-text/README.mdnew file mode 100644index 00000000..2097f0d4--- /dev/null+++ b/animations/05-text-typography/wavy-text/README.md@@ -0,0 +1,56 @@+# Wavy Text++## What it is+Wavy text sends a vertical sine wave rolling across a word. Each character bobs up and down on the same keyframe, but neighbouring letters are offset in time, so the peak of the motion travels from the first letter to the last — like a flag ripple or a row of buoys lifted by a passing swell.++## When to use it+- Playful headlines and logotypes for games, kids' products, or casual brands+- Loading and idle states that want gentle life without demanding attention+- Hover accents where a word "comes alive" on interaction+- Music, party, or beach-themed sites where a liquid feel fits the tone++## How it works+JavaScript splits the string into one `<span>` per character and stamps each with an index custom property `--i`. Every span shares a single `bob` keyframe that translates it on the Y axis; the per-letter `animation-delay` of `--i × stagger` phases each letter behind its neighbour, producing the travelling wave:++```js+[...str].forEach((ch,i)=>{+ const s=document.createElement('span');+ s.textContent=ch===' '?' ':ch;+ s.style.setProperty('--i',i);+ wave.appendChild(s);+});+```++```css+.wave-text span{+ display:inline-block;+ animation:bob var(--dur) ease-in-out infinite;+ animation-delay:calc(var(--i) * var(--stagger));+}+@keyframes bob{+ 0%,100%{transform:translateY(calc(var(--amp) * .6))}+ 50%{transform:translateY(calc(var(--amp) * -1))}+}+```++Only `transform` animates, so the effect stays on the compositor and runs at 60fps. Amplitude, duration, and stagger are all CSS variables the controls rewrite live.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Amplitude | 16px | Vertical travel of each letter; larger = taller wave |+| Wave speed | 1.6s | Duration of one bob cycle; shorter = faster ripple |+| Stagger | 60ms | Delay between adjacent letters; larger = longer, more visible wave |+| Text | user string | The word split into spans; spaces are preserved as gaps |++## Production notes+- **Accessibility**: splitting text into spans destroys the readable word for assistive tech. The demo sets `aria-label` on the container and `aria-hidden="true"` on each fragment, so screen readers announce the whole word once instead of spelling it out letter by letter.+- **Reduced motion**: under `@media (prefers-reduced-motion: reduce)` the span animation and transform are disabled, leaving flat, static text. Vestibular users get no bobbing.+- **Layout**: use `display:inline-block` on the spans (bare inline elements ignore `transform`) and `white-space:pre` on the container so spaces don't collapse. Emoji and combining characters can break naive `[...str]` splitting — segment with `Intl.Segmenter` if the text is user-supplied.+- **Library equivalents**: GSAP SplitText handles the character splitting and offers a `stagger` option on its tweens; Splitting.js emits `--char-index` custom properties equivalent to the `--i` here, letting you drive the same effect in pure CSS.++## See also+- [Kinetic Typography](../kinetic-typography/) — the broader family of per-letter motion+- [Typewriter Effect](../typewriter-effect/) — another per-character reveal technique+- [Text Morphing](../text-morphing/) — animating letterforms rather than their position+- [Variable Font Morph](../variable-font-morph/) — animating type via font axesdiff --git a/animations/05-text-typography/wavy-text/index.html b/animations/05-text-typography/wavy-text/index.htmlnew file mode 100644index 00000000..fc6d1c17--- /dev/null+++ b/animations/05-text-typography/wavy-text/index.html@@ -0,0 +1,102 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Wavy Text</title>+ <style>+ :root{+ --bg:#0b0b0d;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#ff6f8b;+ --ui-text:#f4f4f2;--ui-muted:#77777e;+ --disp:'Arial Narrow','Segoe UI',system-ui,sans-serif;--mono:ui-monospace,Menlo,Consolas,monospace;+ --stage-h:520px;--amp:16px;--dur:1.6s;--stagger:60ms;+ }+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:var(--mono);-webkit-font-smoothing:antialiased;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ header h1{font-family:var(--disp);font-weight:800;font-size:clamp(16px,2.2vw,22px);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;+ background:radial-gradient(circle at 50% 45%,#101018,#04060c);display:flex;align-items:center;justify-content:center;padding:24px;overflow:hidden}+ .wave-text{font-family:var(--disp);font-weight:800;font-size:clamp(40px,11vw,110px);+ line-height:1;letter-spacing:.01em;color:#fff;white-space:pre;-webkit-user-select:none;user-select:none}+ /* each character is its own span, offset in the wave by --i * stagger */+ .wave-text span{display:inline-block;will-change:transform;+ animation:bob var(--dur) ease-in-out infinite;+ animation-delay:calc(var(--i) * var(--stagger))}+ @keyframes bob{+ 0%,100%{transform:translateY(calc(var(--amp) * .6))}+ 50%{transform:translateY(calc(var(--amp) * -1))}+ }+ 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)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:44px;text-align:right;color:var(--ui-text)}+ input[type=text]{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:var(--mono);font-size:11px;padding:8px 10px;border-radius:4px;width:100%;min-height:44px;outline:none}+ input[type=text]:focus{border-color:var(--ui-accent)}+ .div{height:1px;background:var(--ui-border)}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:auto}.stage{height:auto;min-height:340px}}+ @media(prefers-reduced-motion:reduce){+ .wave-text span{animation:none!important;transform:none!important}+ }+ </style>+</head>+<body>+<header>+ <h1>Wavy Text</h1>+ <p>Each letter is its own span with a staggered animation-delay, so a vertical sine wave travels across the word.</p>+</header>+<div class="layout">+ <div class="stage">+ <div class="wave-text" id="wave" aria-label="Wavy">Wavy</div>+ </div>+ <aside>+ <p class="note">JS splits the string into per-letter spans and sets a --i index on each. A shared bob keyframe plus a delay of i × stagger phases neighbours apart, producing a rolling wave.</p>+ <div class="lbl">Text</div>+ <input type="text" id="text-inp" value="Wavy" maxlength="14">+ <div class="lbl">Amplitude</div>+ <div class="sr"><input type="range" id="amp-sl" min="4" max="40" value="16" step="2"><span class="sv" id="amp-sv">16px</span></div>+ <div class="lbl">Wave speed</div>+ <div class="sr"><input type="range" id="spd-sl" min="1" max="10" value="6" step="1"><span class="sv" id="spd-sv">1.6s</span></div>+ <div class="lbl">Per-letter stagger</div>+ <div class="sr"><input type="range" id="stg-sl" min="0" max="160" value="60" step="10"><span class="sv" id="stg-sv">60ms</span></div>+ </aside>+</div>+<script>+const wave=document.getElementById('wave');+const root=document.documentElement;++// Split the string into spans, preserving spaces, and index each with --i.+function build(str){+ wave.setAttribute('aria-label',str);+ wave.textContent='';+ [...str].forEach((ch,i)=>{+ const s=document.createElement('span');+ s.textContent=ch===' '?' ':ch;+ s.style.setProperty('--i',i);+ s.setAttribute('aria-hidden','true');+ wave.appendChild(s);+ });+}+build('Wavy');++document.getElementById('text-inp').addEventListener('input',e=>build(e.target.value||' '));+document.getElementById('amp-sl').addEventListener('input',e=>{+ root.style.setProperty('--amp',e.target.value+'px');+ document.getElementById('amp-sv').textContent=e.target.value+'px';+});+document.getElementById('spd-sl').addEventListener('input',e=>{+ const dur=(11-+e.target.value)*0.28;+ root.style.setProperty('--dur',dur.toFixed(1)+'s');+ document.getElementById('spd-sv').textContent=dur.toFixed(1)+'s';+});+document.getElementById('stg-sl').addEventListener('input',e=>{+ root.style.setProperty('--stagger',e.target.value+'ms');+ document.getElementById('stg-sv').textContent=e.target.value+'ms';+});+</script>+</body>+</html>diff --git a/animations/06-3d-advanced/README.md b/animations/06-3d-advanced/README.mdindex fe2e210d..252b2e31 100644--- a/animations/06-3d-advanced/README.md+++ b/animations/06-3d-advanced/README.md@@ -22,6 +22,7 @@ WebGL, shaders, particles, 3D transforms, and the performance-sensitive effects| [Image Distortion on Hover](image-distortion-hover/) | Fragment shader displaces UV coordinates around the cursor — four distortion types || [Cloth Simulation](cloth-simulation/) | Verlet integration + distance constraints — draggable, gravity, and wind-responsive || [Volumetric Smoke](volumetric-smoke/) | Ray marching that accumulates 3D noise density — light scattering, shadow rays |+| [Morphing Blob](morphing-blob/) | Metaball circles fused by an SVG blur-plus-contrast filter — drifts and a droplet chases the pointer |## Key conceptsdiff --git a/animations/06-3d-advanced/morphing-blob/README.md b/animations/06-3d-advanced/morphing-blob/README.mdnew file mode 100644index 00000000..77353460--- /dev/null+++ b/animations/06-3d-advanced/morphing-blob/README.md@@ -0,0 +1,57 @@+# Morphing Blob++## What it is+A morphing blob is a soft, organic shape that continuously reshapes itself and, when interactive, reacts to the pointer. The classic web technique renders several plain circles ("metaballs") and passes them through an SVG filter that makes overlapping circles fuse into a single liquid silhouette. As the circles move, the blob appears to melt, stretch, and split like a drop of mercury.++## When to use it+- Playful hero backgrounds and landing-page focal points+- Loading and idle states that need to feel alive without being distracting+- Cursor-reactive accents where a shape follows or "grabs" the pointer+- Logo and brand moments that want an organic, non-geometric personality++## How it works+Each blob is a normal SVG `<circle>`. The whole group is passed through a "goo" filter: a Gaussian blur spreads every circle's edge, then a `feColorMatrix` drives the alpha channel through a steep contrast curve, snapping the soft blur back into a hard edge. Where two blurred circles overlap, their combined alpha crosses the threshold and they read as one connected shape.++```html+<filter id="goo">+ <feGaussianBlur in="SourceGraphic" stdDeviation="10" id="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"/>+</filter>+<g filter="url(#goo)" fill="url(#fill)"><!-- circles --></g>+```++The last row of the matrix (`0 0 0 20 -9`) is the trick: it multiplies alpha by 20 and subtracts 9, so mid-range (blurred) alpha collapses to 0 or 1 — a hard silhouette. A requestAnimationFrame loop drifts the background circles on sine paths, while one "droplet" circle eases toward the pointer:++```js+if (b.droplet){ // Pointer Events → works for mouse, pen, touch+ b.x += (pointer.x - b.x) * 0.09; // attraction toward the cursor+ b.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;+}+```++## 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 |+| 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) |++## Production notes+- **Filter performance is the gotcha.** SVG filters rasterise the filter region every frame on the CPU/GPU compositor; a large blurred area over a big viewport can drop frames on mobile. Keep the filtered `<g>` region as small as the design allows, cap `stdDeviation`, and reduce blob count on small screens. Test on a mid-range phone, not just desktop.+- **Safari and blur units.** `stdDeviation` is in user (viewBox) units, not pixels — the visual blur scales with your `viewBox`, so pin the viewBox size and let CSS scale the SVG rather than resizing the viewBox.+- **`will-change: transform`** on the SVG element can promote it to its own layer and smooth things out, but watch memory on low-end devices.+- **Reduced motion.** Under `prefers-reduced-motion: reduce` this demo paints one settled arrangement and stops the idle drift — never leave an autonomous churning shape running for users who opted out.+- **Alternatives / library equivalents:** for a single animated outline instead of metaballs, interpolate an SVG `<path>`'s control points (the approach tools like **blobmaker** / **Haikei** export). For heavy, truly 3D goo, **three.js** MarchingCubes (metaballs) or a ray-marched SDF in a fragment shader gives real volume at GPU cost. **Framer Motion** can tween a `path`'s `d` attribute for path-based blobs.++## See also+- [Fluid Simulation](../fluid-simulation/) — GPU metaballs via SDF smooth-minimum in a shader+- [Noise-Based Motion](../noise-based-motion/) — simplex noise driving a morphing blob outline+- [SVG Path Animation](../svg-path-animation/) — animating the `<path>` data itself+- [Ray Marching / SDF](../ray-marching-sdf/) — the 3D, in-shader cousin of metaball blendingdiff --git a/animations/06-3d-advanced/morphing-blob/index.html b/animations/06-3d-advanced/morphing-blob/index.htmlnew file mode 100644index 00000000..7be68ba1--- /dev/null+++ b/animations/06-3d-advanced/morphing-blob/index.html@@ -0,0 +1,164 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Morphing Blob</title>+ <style>+ :root{+ --bg:#0b0b0d;--stage:#08060e;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);+ --accent:#b98bff;--accent2:#58a6ff;--text:#f4f4f2;--muted:#77777e;+ --mono:ui-monospace,Menlo,Consolas,monospace;--stage-h:min(70vh,620px);+ }+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--text);font-family:var(--mono);-webkit-font-smoothing:antialiased;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:18px}+ header h1{font-size:clamp(18px,3vw,26px);letter-spacing:-.02em}+ header p{font-size:clamp(11px,1.4vw,13px);color:var(--muted);margin-top:6px;max-width:62ch}+ .layout{display:flex;gap:clamp(12px,2vw,22px);align-items:stretch}+ .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:12px;+ background:radial-gradient(circle at 50% 42%,#141024,var(--stage) 70%);overflow:hidden;position:relative;touch-action:none;cursor:crosshair}+ svg{position:absolute;inset:0;width:100%;height:100%;display:block}+ .tip{position:absolute;bottom:12px;left:0;right:0;text-align:center;font-size:11px;letter-spacing:2px;text-transform:uppercase;color:var(--muted);pointer-events:none}+ aside{width:clamp(210px,24vw,250px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:12px;padding:16px;display:flex;flex-direction:column;gap:12px}+ .note{font-size:10px;color:var(--muted);line-height:1.6;border-left:2px solid var(--accent);padding-left:8px}+ .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--accent)}+ .row{display:flex;align-items:center;gap:8px}+ input[type=range]{flex:1;accent-color:var(--accent);min-height:44px}+ .sv{width:44px;text-align:right;font-size:12px;color:var(--text)}+ .div{height:1px;background:var(--ui-border)}+ .kv{display:flex;justify-content:space-between;font-size:10px;color:var(--muted)}+ .kv .v{color:var(--text)}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:56vh}}+ @media(prefers-reduced-motion:reduce){.tip{display:none}}+ </style>+</head>+<body>+<header>+ <h1>Morphing Blob</h1>+ <p>An organic gooey blob built from metaball circles fused by an SVG blur-plus-contrast filter — it drifts on its own and a droplet chases your pointer, merging and splitting like liquid.</p>+</header>++<div class="layout">+ <div class="stage" id="stage">+ <svg id="svg" viewBox="0 0 400 400" preserveAspectRatio="xMidYMid slice" aria-hidden="true">+ <defs>+ <!-- The "goo": blur spreads the circles, then the alpha channel is+ pushed through a steep contrast curve so soft edges snap back to a+ hard silhouette — overlapping circles fuse into one liquid shape. -->+ <filter id="goo">+ <feGaussianBlur in="SourceGraphic" stdDeviation="10" id="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"/>+ </filter>+ <linearGradient id="fill" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0" stop-color="#b98bff"/>+ <stop offset="1" stop-color="#58a6ff"/>+ </linearGradient>+ </defs>+ <g id="blobs" filter="url(#goo)" fill="url(#fill)"></g>+ </svg>+ <div class="tip" id="tip">Move your pointer</div>+ </div>++ <aside>+ <p class="note">No shaders and no libraries — the whole liquid effect is one SVG filter over plain moving circles. Blur softens, the color-matrix re-hardens the edge, and the metaballs appear to melt together.</p>+ <div class="lbl">Gooeyness (blur)</div>+ <div class="row"><input type="range" id="goo" min="4" max="22" step="1" value="10"><span class="sv" id="gooV">10</span></div>+ <div class="lbl">Blob count</div>+ <div class="row"><input type="range" id="count" min="3" max="10" step="1" value="6"><span class="sv" id="countV">6</span></div>+ <div class="lbl">Drift speed</div>+ <div class="row"><input type="range" id="speed" min="0" max="200" step="1" value="100"><span class="sv" id="speedV">1.0</span></div>+ <div class="div"></div>+ <div class="kv"><span>Technique</span><span class="v">metaballs</span></div>+ <div class="kv"><span>Filter</span><span class="v">blur + contrast</span></div>+ <div class="kv"><span>Droplet</span><span class="v">pointer-tracked</span></div>+ </aside>+</div>++<script>+const NS='http://www.w3.org/2000/svg';+const group=document.getElementById('blobs'),blur=document.getElementById('blur'),tip=document.getElementById('tip');+const gooEl=document.getElementById('goo'),gooV=document.getElementById('gooV');+const countEl=document.getElementById('count'),countV=document.getElementById('countV');+const speedEl=document.getElementById('speed'),speedV=document.getElementById('speedV');+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 pointer={x:CX,y:CY,active:false}; // target for the droplet, in viewBox units++function build(n){+ group.textContent='';+ blobs=[];+ for(let i=0;i<n;i++){+ const el=document.createElementNS(NS,'circle');+ group.appendChild(el);+ if(i===0){+ // The droplet: chases the pointer instead of drifting.+ blobs.push({el,droplet:true,x:CX,y:CY,r:34});+ }else{+ const ang=(i/n)*Math.PI*2, orbit=58+Math.random()*30;+ blobs.push({el,droplet:false,+ bx:CX+Math.cos(ang)*orbit, by:CY+Math.sin(ang)*orbit,+ r:26+Math.random()*26,+ ax:20+Math.random()*34, ay:20+Math.random()*34, // wander amplitude+ px:Math.random()*6.28, py:Math.random()*6.28, // phase+ sx:0.4+Math.random()*0.6, sy:0.4+Math.random()*0.6, // per-axis rate+ x:CX,y:CY});+ }+ }+}++function frame(t){+ const time=t/1000;+ 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;+ 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;+ }+ b.el.setAttribute('cx',b.x.toFixed(2));+ b.el.setAttribute('cy',b.y.toFixed(2));+ b.el.setAttribute('r',b.r.toFixed(2));+ }+ raf=requestAnimationFrame(frame);+}++// Pointer Events cover mouse, pen and touch with one code path.+function toViewBox(e){+ const r=stage.getBoundingClientRect();+ // slice-scaled square viewBox: map to the larger dimension, centre the shorter+ const side=Math.max(r.width,r.height);+ const ox=(r.width-side)/2, oy=(r.height-side)/2;+ pointer.x=((e.clientX-r.left-ox)/side)*400;+ pointer.y=((e.clientY-r.top-oy)/side)*400;+ pointer.active=true;tip.style.opacity=0;+}+stage.addEventListener('pointermove',toViewBox);+stage.addEventListener('pointerdown',toViewBox);+stage.addEventListener('pointerleave',()=>{pointer.x=CX;pointer.y=CY;});++gooEl.addEventListener('input',e=>{blur.setAttribute('stdDeviation',e.target.value);gooV.textContent=e.target.value;});+countEl.addEventListener('input',e=>{countV.textContent=e.target.value;build(+e.target.value);if(reduce)paintStatic();});+speedEl.addEventListener('input',e=>{speed=e.target.value/100;speedV.textContent=speed.toFixed(1);});++build(+countEl.value);+let raf=null;+function paintStatic(){ // one settled arrangement, no idle motion+ for(const b of blobs){+ b.el.setAttribute('cx',(b.droplet?CX:b.bx).toFixed(2));+ b.el.setAttribute('cy',(b.droplet?CY:b.by).toFixed(2));+ b.el.setAttribute('r',b.r.toFixed(2));+ }+}+if(reduce){speed=0;paintStatic();}+else{raf=requestAnimationFrame(frame);}+</script>+</body>+</html>diff --git a/animations/07-ambient-background/README.md b/animations/07-ambient-background/README.mdindex 9d61c272..18d1faa5 100644--- a/animations/07-ambient-background/README.md+++ b/animations/07-ambient-background/README.md@@ -18,6 +18,9 @@ Passive, looping effects that hold visual interest without demanding attention.| [Floating Elements](floating-elements/) | Geometric shapes drift on independent sine-wave paths — SaaS hero pattern || [Grid / Dot Pattern Parallax](grid-dot-pattern-parallax/) | Pattern shifts subtly opposite to mouse — depth felt, not seen || [Abstract Geometric Motion](abstract-geometric-motion/) | Four hypnotic loops — polygons, rings, bars, flowing lines |+| [Particle Constellation](particle-constellation/) | Drifting nodes link with lines when they come close — the network-mesh hero background |+| [Flow Field](flow-field/) | Particles follow a noise-driven vector field, leaving flowing trails |+| [Synthwave Grid](synthwave-grid/) | A perspective grid scrolls toward a glowing sun — the retro synthwave horizon |## The ambient mindsetdiff --git a/animations/07-ambient-background/flow-field/README.md b/animations/07-ambient-background/flow-field/README.mdnew file mode 100644index 00000000..95ccd2f1--- /dev/null+++ b/animations/07-ambient-background/flow-field/README.md@@ -0,0 +1,51 @@+# Flow Field++## What it is+Thousands of particles crawl across the canvas, each one steering by the angle of an invisible vector field. The field comes from a small noise function, so neighbouring particles curve in unison and the whole surface reveals smooth, river-like currents. Because the frame is dimmed rather than cleared, particles leave fading trails that trace the flow.++## When to use it+- Generative, organic hero backgrounds where every load looks slightly different+- Data-art and creative-coding pieces+- Ambient loops behind dark landing pages that want texture, not a subject+- Transitions or loading screens that benefit from continuous motion++## How it works+There is no stored field — an angle is computed on demand from an inline value-noise function (a hashed lattice, smooth-interpolated). Each particle samples the angle beneath it, steps that direction, and respawns when it leaves the canvas. Trails come from painting a translucent background instead of clearing:++```js+function vnoise(x, y) {+ const xi = Math.floor(x), yi = Math.floor(y), xf = x - xi, yf = y - yi;+ const tl = hash(xi,yi), tr = hash(xi+1,yi), bl = hash(xi,yi+1), br = hash(xi+1,yi+1);+ const u = smooth(xf), v = smooth(yf);+ return (tl*(1-u)+tr*u)*(1-v) + (bl*(1-u)+br*u)*v;+}+function angleAt(x, y, time) {+ return vnoise(x/SCALE, y/SCALE + time*0.15) * Math.PI * 4;+}++// per frame: fade, then advance every particle along its local angle+ctx.fillStyle = `rgba(5,6,10,${TRAIL})`; ctx.fillRect(0, 0, W, H);+const a = angleAt(p.x, p.y, t);+p.x += Math.cos(a) * SPD; p.y += Math.sin(a) * SPD;+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Particle count | 900 | Density of the trails; the main cost driver |+| Noise scale | 34 | Larger = broader, calmer currents; smaller = tight turbulence |+| Speed | 1.0 | Step length per frame; higher smears the trails |+| Trail persistence | 0.06 | Fade alpha — low = long ghostly trails, high = short crisp ones |+| Color | mint | Fixed hue, or `spectrum` for a hue that maps to x-position |++## Production notes+- **Trail alpha vs. buildup**: because trails rely on incomplete clearing, a very low persistence value can leave permanent residue on some GPUs. Nudge it up (0.04+) if you see ghosting that never fully fades.+- **Mobile cap**: particle count is limited to 500 under 600px. Each particle is a stroked line segment, so fill rate — not math — is the bottleneck on phones.+- **Deterministic noise**: the `hash` uses `sin(x*127.1 + y*311.7)*43758.5453`, a classic GLSL trick. It is not cryptographic and not true Perlin noise, but it is cheap, dependency-free, and smooth enough for a field.+- **Reduced motion**: on `prefers-reduced-motion`, the loop is skipped and ~40 frames are pre-rendered once to leave a static, settled composition.+- **Library equivalents**: production flow fields usually run on the GPU — [three.js](https://threejs.org) with a fragment/compute shader, or curl-noise in a particle system. [tsParticles](https://github.com/matteobruni/tsparticles) does not do true flow fields, but its path plugins approximate directed motion.++## See also+- [Particle Constellation](../particle-constellation/) — particles that link rather than flow+- [Aurora](../aurora/) — flowing colour bands from blur instead of particles+- [Mesh Gradient](../mesh-gradient/) — smooth drifting colour with no discrete particlesdiff --git a/animations/07-ambient-background/flow-field/index.html b/animations/07-ambient-background/flow-field/index.htmlnew file mode 100644index 00000000..6d74ca92--- /dev/null+++ b/animations/07-ambient-background/flow-field/index.html@@ -0,0 +1,137 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Flow Field</title>+ <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:'PlexMono';src:url('../../../assets/fonts/plex-400.woff2') format('woff2');font-weight:400;font-display:swap}+ :root{--bg:#0b0b0d;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#7affc8;--ui-text:#f4f4f2;--ui-muted:#77777e;--disp:'Bricolage','Arial Narrow',sans-serif;--mono:'PlexMono',ui-monospace,Menlo,Consolas,monospace;--stage-h:620px}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:var(--mono);-webkit-font-smoothing:antialiased;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ 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;background:#05060a}+ canvas{display:block;width:100%;height:100%}+ .fps-badge{position:absolute;top:8px;right:8px;font-size:9px;color:rgba(255,255,255,.4);background:rgba(0,0,0,.5);padding:3px 8px;border-radius:4px;pointer-events:none}+ 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)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:44px;text-align:right;color:var(--ui-text)}+ select{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:8px 6px;border-radius:4px;width:100%;min-height:44px}+ button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}+ @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:380px}}+ @media(prefers-reduced-motion:reduce){.fps-badge{display:none}}+ </style>+</head>+<body>+<header>+ <h1>Flow Field</h1>+ <p>Particles ride a vector field sampled from inline pseudo-noise, leaving fading trails that map the invisible currents.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <canvas id="cvs"></canvas>+ <div class="fps-badge" id="fps">— fps</div>+ </div>+ <aside>+ <p class="note">There is no image here — only a math function that returns an angle for every point on screen. Each particle reads the angle under it and steps that way. Trails appear because the frame is dimmed, not cleared.</p>+ <div class="lbl">Particle Count</div>+ <div class="sr"><input type="range" id="count-sl" min="200" max="2000" value="900" step="100"><span class="sv" id="count-v">900</span></div>+ <div class="lbl">Noise Scale</div>+ <div class="sr"><input type="range" id="scale-sl" min="10" max="80" value="34" step="2"><span class="sv" id="scale-v">34</span></div>+ <div class="lbl">Speed</div>+ <div class="sr"><input type="range" id="spd-sl" min="2" max="30" value="10" step="1"><span class="sv" id="spd-v">1.0</span></div>+ <div class="lbl">Trail Persistence</div>+ <div class="sr"><input type="range" id="trail-sl" min="1" max="14" value="6" step="1"><span class="sv" id="trail-v">0.06</span></div>+ <div class="lbl">Color</div>+ <select id="col-sel">+ <option value="mint" selected>Mint</option>+ <option value="ember">Ember</option>+ <option value="ice">Ice</option>+ <option value="spectrum">Spectrum</option>+ </select>+ <div class="div"></div>+ <div style="font-size:9px;color:var(--ui-muted)">Count caps at 500 on small screens.</div>+ <button class="rst" id="pause-btn">⏸ Pause</button>+ </aside>+</div>+<script>+const cvs=document.getElementById('cvs'),ctx=cvs.getContext('2d');+const stage=document.getElementById('stage'),fpsEl=document.getElementById('fps');+let W,H,paused=false,raf=null,lastT=0,t=0;+let COUNT=900,SCALE=34,SPD=1.0,TRAIL=0.06,COL='mint';+let parts=[];+const reduce=window.matchMedia('(prefers-reduced-motion:reduce)').matches;++// tiny deterministic value-noise: hash a lattice, smooth-interpolate, return an angle.+function hash(x,y){const s=Math.sin(x*127.1+y*311.7)*43758.5453;return s-Math.floor(s);}+function smooth(t){return t*t*(3-2*t);}+function vnoise(x,y){+ const xi=Math.floor(x),yi=Math.floor(y),xf=x-xi,yf=y-yi;+ const tl=hash(xi,yi),tr=hash(xi+1,yi),bl=hash(xi,yi+1),br=hash(xi+1,yi+1);+ const u=smooth(xf),v=smooth(yf);+ return (tl*(1-u)+tr*u)*(1-v)+(bl*(1-u)+br*u)*v;+}+function angleAt(x,y,time){+ const n=vnoise(x/SCALE,y/SCALE+time*0.15);+ return n*Math.PI*4; // map [0,1] noise to a couple of full turns+}++function effCount(){return W<600?Math.min(COUNT,500):COUNT;}+function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;init();ctx.fillStyle='#05060a';ctx.fillRect(0,0,W,H);}+function init(){parts=Array.from({length:effCount()},()=>({x:Math.random()*W,y:Math.random()*H}));}++function colorFor(p){+ if(COL==='mint')return'rgba(122,255,200,.5)';+ if(COL==='ember')return'rgba(255,150,80,.5)';+ if(COL==='ice')return'rgba(120,190,255,.5)';+ return`hsla(${(p.x/W*120+t*20)%360},80%,65%,.5)`;+}++function frame(){+ // translucent fill instead of clear -> old pixels fade, forming trails+ ctx.fillStyle=`rgba(5,6,10,${TRAIL})`;ctx.fillRect(0,0,W,H);+ for(const p of parts){+ const a=angleAt(p.x,p.y,t);+ const nx=p.x+Math.cos(a)*SPD,ny=p.y+Math.sin(a)*SPD;+ ctx.strokeStyle=colorFor(p);ctx.lineWidth=1;+ ctx.beginPath();ctx.moveTo(p.x,p.y);ctx.lineTo(nx,ny);ctx.stroke();+ p.x=nx;p.y=ny;+ if(p.x<0||p.x>W||p.y<0||p.y>H){p.x=Math.random()*W;p.y=Math.random()*H;}+ }+ t+=0.01;+}++function loop(ts){+ if(paused){raf=null;return;}+ raf=requestAnimationFrame(loop);+ const dt=ts-lastT;if(dt<16)return;lastT=ts;+ fpsEl.textContent=Math.round(1000/(dt||16))+' fps';+ frame();+}++resize();+if(reduce){for(let i=0;i<40;i++)frame();fpsEl.textContent='static';}+else raf=requestAnimationFrame(loop);+window.addEventListener('resize',resize);++document.getElementById('count-sl').addEventListener('input',e=>{COUNT=+e.target.value;document.getElementById('count-v').textContent=COUNT;init();});+document.getElementById('scale-sl').addEventListener('input',e=>{SCALE=+e.target.value;document.getElementById('scale-v').textContent=SCALE;});+document.getElementById('spd-sl').addEventListener('input',e=>{SPD=e.target.value/10;document.getElementById('spd-v').textContent=SPD.toFixed(1);});+document.getElementById('trail-sl').addEventListener('input',e=>{TRAIL=e.target.value/100;document.getElementById('trail-v').textContent=TRAIL.toFixed(2);});+document.getElementById('col-sel').addEventListener('change',e=>{COL=e.target.value;});+document.getElementById('pause-btn').addEventListener('click',()=>{+ paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';+ if(!paused){lastT=performance.now();raf=requestAnimationFrame(loop);}+});+</script>+</body>+</html>diff --git a/animations/07-ambient-background/particle-constellation/README.md b/animations/07-ambient-background/particle-constellation/README.mdnew file mode 100644index 00000000..4c83057c--- /dev/null+++ b/animations/07-ambient-background/particle-constellation/README.md@@ -0,0 +1,51 @@+# Particle Constellation++## What it is+A field of small nodes drifts slowly across a canvas, and any two nodes closer than a set distance are joined by a line whose opacity fades as they separate. The result is a shifting network mesh — the "connected dots" hero background seen behind countless product and crypto landing pages.++## When to use it+- Hero sections for tech, network, security, or data products+- Loading and idle states that need life without a focal point+- Backgrounds behind headline text, where subtle motion adds depth+- Anywhere a "connected system" metaphor reinforces the message++## How it works+Nodes are plain objects with a position and velocity; they drift and bounce off the edges. Every frame, a double loop tests each pair — when the squared distance falls under the link threshold, a line is drawn with opacity proportional to closeness. Using squared distance avoids a `sqrt` in the reject case:++```js+const L2 = LINK * LINK;+for (let i = 0; i < nodes.length; i++) {+ const a = nodes[i];+ for (let j = i + 1; j < nodes.length; j++) {+ const b = nodes[j], dx = a.x - b.x, dy = a.y - b.y, d2 = dx*dx + dy*dy;+ if (d2 < L2) {+ const op = (1 - Math.sqrt(d2) / LINK) * 0.55;+ ctx.strokeStyle = `rgba(${c[0]},${c[1]},${c[2]},${op})`;+ ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke();+ }+ }+}+```++Optional mouse attraction nudges each node's velocity toward the pointer, so the mesh gathers where the cursor rests.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Node count | 90 | Line tests grow as count², so this dominates cost |+| Link distance | 130px | Larger = denser web; too large and everything connects to everything |+| Drift speed | 0.6 | Ambient range is 0.3–1.0; above that it reads as agitated |+| Mouse attraction | on | Pull strength is capped and damped so it stays gentle |+| Color | cyan | RGB triple reused for both nodes and lines |++## Production notes+- **The n² wall**: connection testing is O(n²). At ~150 nodes you are doing >11,000 distance checks per frame. This demo caps nodes at 60 on screens under 600px to hold 60fps on mid-range phones. For larger fields, bucket nodes into a spatial grid and only test neighboring cells.+- **Velocity damping**: multiplying velocity by 0.99 each frame keeps the mouse-attraction impulses from accumulating into runaway speeds — without it, the field slowly boils.+- **Reduced motion**: the animation loop never starts; a single static frame is drawn and re-rendered only when a control changes, honoring `prefers-reduced-motion`.+- **Retina**: for crisp lines on high-DPI screens, scale the canvas backing store by `devicePixelRatio` and the context by the same factor. Omitted here to keep fill rate low on mobile.+- **Library equivalents**: [tsParticles](https://github.com/matteobruni/tsparticles) ships this exact effect (`links` mode) with presets; [three.js](https://threejs.org) can push the same idea to tens of thousands of GPU points with `LineSegments`.++## See also+- [Starfield](../starfield/) — particles as depth rather than a network+- [Floating Elements](../floating-elements/) — drifting shapes on independent paths+- [Grid / Dot Pattern Parallax](../grid-dot-pattern-parallax/) — a static lattice that reacts to the mousediff --git a/animations/07-ambient-background/particle-constellation/index.html b/animations/07-ambient-background/particle-constellation/index.htmlnew file mode 100644index 00000000..ea76c348--- /dev/null+++ b/animations/07-ambient-background/particle-constellation/index.html@@ -0,0 +1,148 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Particle Constellation</title>+ <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:'PlexMono';src:url('../../../assets/fonts/plex-400.woff2') format('woff2');font-weight:400;font-display:swap}+ :root{--bg:#0b0b0d;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#5ad1ff;--ui-text:#f4f4f2;--ui-muted:#77777e;--disp:'Bricolage','Arial Narrow',sans-serif;--mono:'PlexMono',ui-monospace,Menlo,Consolas,monospace;--stage-h:620px}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:var(--mono);-webkit-font-smoothing:antialiased;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ 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;background:#06070c}+ canvas{display:block;width:100%;height:100%}+ .fps-badge{position:absolute;top:8px;right:8px;font-size:9px;color:rgba(255,255,255,.4);background:rgba(0,0,0,.5);padding:3px 8px;border-radius:4px;pointer-events:none}+ 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)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:44px;text-align:right;color:var(--ui-text)}+ select{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:8px 6px;border-radius:4px;width:100%;min-height:44px}+ .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}+ button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}+ @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:380px}}+ @media(prefers-reduced-motion:reduce){.fps-badge{display:none}}+ </style>+</head>+<body>+<header>+ <h1>Particle Constellation</h1>+ <p>Drifting nodes link to nearby neighbors — line opacity fades with distance, building a living network mesh.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <canvas id="cvs"></canvas>+ <div class="fps-badge" id="fps">— fps</div>+ </div>+ <aside>+ <p class="note">The whole effect is one rule: for every pair of nodes closer than the link distance, draw a line whose opacity is proportional to how close they are. Nodes never touch — the connections do the work.</p>+ <div class="lbl">Node Count</div>+ <div class="sr"><input type="range" id="count-sl" min="20" max="160" value="90" step="10"><span class="sv" id="count-v">90</span></div>+ <div class="lbl">Link Distance</div>+ <div class="sr"><input type="range" id="link-sl" min="60" max="220" value="130" step="10"><span class="sv" id="link-v">130</span></div>+ <div class="lbl">Drift Speed</div>+ <div class="sr"><input type="range" id="spd-sl" min="1" max="20" value="6" step="1"><span class="sv" id="spd-v">0.6</span></div>+ <div class="lbl">Color</div>+ <select id="col-sel">+ <option value="cyan" selected>Cyan</option>+ <option value="violet">Violet</option>+ <option value="mint">Mint</option>+ <option value="mono">Monochrome</option>+ </select>+ <label class="tog"><input type="checkbox" id="mouse-tog" checked><span>Mouse attraction</span></label>+ <div class="div"></div>+ <div style="font-size:9px;color:var(--ui-muted)">Nodes cap at 60 on small screens for 60fps.</div>+ <button class="rst" id="pause-btn">⏸ Pause</button>+ </aside>+</div>+<script>+const cvs=document.getElementById('cvs'),ctx=cvs.getContext('2d');+const stage=document.getElementById('stage'),fpsEl=document.getElementById('fps');+let W,H,paused=false,raf=null,lastT=0;+let COUNT=90,LINK=130,SPD=0.6,COL='cyan',MOUSE=true;+let nodes=[],mx=-999,my=-999;+const PAL={cyan:[90,209,255],violet:[168,130,255],mint:[122,255,200],mono:[220,220,225]};+const reduce=window.matchMedia('(prefers-reduced-motion:reduce)').matches;++function effCount(){return W<600?Math.min(COUNT,60):COUNT;}+function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;init();}++function init(){+ const n=effCount();+ nodes=Array.from({length:n},()=>({+ x:Math.random()*W,y:Math.random()*H,+ vx:(Math.random()-.5),vy:(Math.random()-.5),+ r:Math.random()*1.4+1+ }));+}++function step(){+ for(const p of nodes){+ p.x+=p.vx*SPD;p.y+=p.vy*SPD;+ if(MOUSE&&mx>-500){+ const dx=mx-p.x,dy=my-p.y,d2=dx*dx+dy*dy;+ if(d2<26000&&d2>1){const f=.04/Math.sqrt(d2);p.vx+=dx*f;p.vy+=dy*f;}+ }+ // gentle damping keeps velocities bounded so drift stays ambient+ p.vx*=.99;p.vy*=.99;+ if(p.x<0||p.x>W)p.vx*=-1;if(p.y<0||p.y>H)p.vy*=-1;+ p.x=Math.max(0,Math.min(W,p.x));p.y=Math.max(0,Math.min(H,p.y));+ }+}++function draw(){+ ctx.clearRect(0,0,W,H);+ const c=PAL[COL],L2=LINK*LINK;+ for(let i=0;i<nodes.length;i++){+ const a=nodes[i];+ for(let j=i+1;j<nodes.length;j++){+ const b=nodes[j],dx=a.x-b.x,dy=a.y-b.y,d2=dx*dx+dy*dy;+ if(d2<L2){+ const op=(1-Math.sqrt(d2)/LINK)*.55;+ ctx.strokeStyle=`rgba(${c[0]},${c[1]},${c[2]},${op})`;+ ctx.lineWidth=1;+ ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.stroke();+ }+ }+ }+ ctx.fillStyle=`rgba(${c[0]},${c[1]},${c[2]},.9)`;+ for(const p of nodes){ctx.beginPath();ctx.arc(p.x,p.y,p.r,0,Math.PI*2);ctx.fill();}+}++function loop(ts){+ if(paused){raf=null;return;}+ raf=requestAnimationFrame(loop);+ const dt=ts-lastT;if(dt<16)return;lastT=ts;+ fpsEl.textContent=Math.round(1000/(dt||16))+' fps';+ step();draw();+}++resize();+if(reduce){step();draw();fpsEl.textContent='static';}+else raf=requestAnimationFrame(loop);+window.addEventListener('resize',resize);++stage.addEventListener('pointermove',e=>{const r=stage.getBoundingClientRect();mx=e.clientX-r.left;my=e.clientY-r.top;});+stage.addEventListener('pointerleave',()=>{mx=my=-999;});++document.getElementById('count-sl').addEventListener('input',e=>{COUNT=+e.target.value;document.getElementById('count-v').textContent=COUNT;init();if(reduce){draw();}});+document.getElementById('link-sl').addEventListener('input',e=>{LINK=+e.target.value;document.getElementById('link-v').textContent=LINK;if(reduce){draw();}});+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=>{COL=e.target.value;if(reduce){draw();}});+document.getElementById('mouse-tog').addEventListener('change',e=>{MOUSE=e.target.checked;});+document.getElementById('pause-btn').addEventListener('click',()=>{+ paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';+ if(!paused){lastT=performance.now();raf=requestAnimationFrame(loop);}+});+</script>+</body>+</html>diff --git a/animations/07-ambient-background/synthwave-grid/README.md b/animations/07-ambient-background/synthwave-grid/README.mdnew file mode 100644index 00000000..bc96039a--- /dev/null+++ b/animations/07-ambient-background/synthwave-grid/README.md@@ -0,0 +1,46 @@+# Synthwave Grid++## What it is+A neon wireframe floor stretches to a horizon and scrolls continuously toward the viewer, set against a purple gradient sky with a banded, glowing sun. It is the retro-futurist / outrun aesthetic — the "1984 idea of the future" — rebuilt as a seamless ambient loop on a single canvas.++## When to use it+- Music, gaming, and event landing pages with a retro or vaporwave theme+- Hero backgrounds that want a strong sense of depth and forward motion+- 80s-styled product launches, playlists, or promo screens+- Loops behind large display type, where the grid recedes below the text++## How it works+The floor is drawn in perspective: vertical lines fan out from a vanishing point on the horizon, and horizontal lines are spaced by a power curve so they bunch up near the horizon and spread near the viewer. Scrolling is just an offset taken modulo the line count, which makes the loop seamless — a line that reaches the bottom is the same as a new one appearing at the horizon:++```js+const hz = horizon(), cx = W / 2;+for (let i = 0; i < DENS; i++) {+ let p = ((i + offset) % DENS) / DENS; // 0 at horizon -> 1 at viewer+ const y = hz + Math.pow(p, 2.2) * (H - hz); // perspective compression+ ctx.globalAlpha = Math.min(1, p * 1.6); // fade in near the horizon+ ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(W, y); ctx.stroke();+}+```++The glow is a canvas `shadowBlur` set to the grid colour; the sun is a clipped semicircle filled with a vertical gradient and striped with background-coloured gaps.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Scroll speed | 1.0 | How fast the floor rushes toward the viewer |+| Line density | 16 | Horizontal line count; also sets the loop period |+| Grid glow color | #ff2fb0 | Stroke and `shadowBlur` colour of the whole grid |+| Perspective power | 2.2 | Exponent on the spacing curve (in code) — higher = flatter horizon |++## Production notes+- **`shadowBlur` is expensive**: canvas shadow-based glow is one of the heavier 2D operations. It is fine for this line count, but if you raise density substantially, drop the shadow and fake the glow with a second, thicker, low-alpha pass of each line.+- **The modulo seam**: fading lines in as `p` approaches 0 hides the pop where a new line spawns at the horizon. Without the alpha ramp you would see it flicker into existence.+- **Reduced motion**: on `prefers-reduced-motion` the scroll offset never advances — a single static grid, sky, and sun are drawn, preserving the look without motion.+- **CSS alternative**: this can also be built with a `transform: perspective()` plane and an animated `background-position` on a repeating linear-gradient, which offloads to the compositor. The canvas version wins on control over per-line fade and glow.+- **Library equivalents**: for a true 3D floor with camera moves and bloom, use [three.js](https://threejs.org) — a `PlaneGeometry` with a wireframe material and an `UnrealBloomPass` gives the authentic glow. [tsParticles](https://github.com/matteobruni/tsparticles) is not suited to structured grids.++## See also+- [Starfield](../starfield/) — the other classic "flying through space" depth loop+- [Scanline](../scanline/) — pair with this for full CRT / retro-monitor treatment+- [Grid / Dot Pattern Parallax](../grid-dot-pattern-parallax/) — a flat grid that reacts to the mouse+- [Animated Gradient Background](../animated-gradient-background/) — the sky gradient on its owndiff --git a/animations/07-ambient-background/synthwave-grid/index.html b/animations/07-ambient-background/synthwave-grid/index.htmlnew file mode 100644index 00000000..b44e2ce3--- /dev/null+++ b/animations/07-ambient-background/synthwave-grid/index.html@@ -0,0 +1,131 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Synthwave Grid</title>+ <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:'PlexMono';src:url('../../../assets/fonts/plex-400.woff2') format('woff2');font-weight:400;font-display:swap}+ :root{--bg:#0b0b0d;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#ff5ca8;--ui-text:#f4f4f2;--ui-muted:#77777e;--disp:'Bricolage','Arial Narrow',sans-serif;--mono:'PlexMono',ui-monospace,Menlo,Consolas,monospace;--stage-h:620px}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ body{background:var(--bg);color:var(--ui-text);font-family:var(--mono);-webkit-font-smoothing:antialiased;padding:clamp(12px,3vw,24px)}+ header{margin-bottom:20px}+ 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;background:#0a0316}+ canvas{display:block;width:100%;height:100%}+ .fps-badge{position:absolute;top:8px;right:8px;font-size:9px;color:rgba(255,255,255,.4);background:rgba(0,0,0,.5);padding:3px 8px;border-radius:4px;pointer-events:none}+ 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)}+ .div{height:1px;background:var(--ui-border)}+ .sr{display:flex;align-items:center;gap:6px;font-size:10px}+ .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}+ .sv{width:44px;text-align:right;color:var(--ui-text)}+ input[type=color]{width:44px;height:44px;padding:0;border:1px solid var(--ui-border);border-radius:4px;background:none;cursor:pointer}+ .row{display:flex;align-items:center;gap:8px;font-size:10px}+ button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}+ @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:380px}}+ @media(prefers-reduced-motion:reduce){.fps-badge{display:none}}+ </style>+</head>+<body>+<header>+ <h1>Synthwave Grid</h1>+ <p>A neon perspective grid scrolls toward the viewer under a gradient sky and glowing sun — the retro-futurist loop.</p>+</header>+<div class="layout">+ <div class="stage" id="stage">+ <canvas id="cvs"></canvas>+ <div class="fps-badge" id="fps">— fps</div>+ </div>+ <aside>+ <p class="note">Horizontal lines are placed by a perspective curve — spacing shrinks toward the horizon. Scrolling only means increasing an offset and taking it modulo the spacing, so the grid loops forever with no seam.</p>+ <div class="lbl">Scroll Speed</div>+ <div class="sr"><input type="range" id="spd-sl" min="1" max="30" value="10" step="1"><span class="sv" id="spd-v">1.0</span></div>+ <div class="lbl">Line Density</div>+ <div class="sr"><input type="range" id="dens-sl" min="8" max="30" value="16" step="1"><span class="sv" id="dens-v">16</span></div>+ <div class="lbl">Grid Glow Color</div>+ <div class="row"><input type="color" id="glow-col" value="#ff2fb0"><span id="glow-hex">#ff2fb0</span></div>+ <div class="div"></div>+ <div style="font-size:9px;color:var(--ui-muted)">Sun and sky bands are static gradients; only the grid animates.</div>+ <button class="rst" id="pause-btn">⏸ Pause</button>+ </aside>+</div>+<script>+const cvs=document.getElementById('cvs'),ctx=cvs.getContext('2d');+const stage=document.getElementById('stage'),fpsEl=document.getElementById('fps');+let W,H,paused=false,raf=null,lastT=0,offset=0;+let SPD=1.0,DENS=16,GLOW='#ff2fb0';+const reduce=window.matchMedia('(prefers-reduced-motion:reduce)').matches;++function resize(){W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;}+function horizon(){return H*0.42;}++function drawSky(){+ const hz=horizon();+ const sky=ctx.createLinearGradient(0,0,0,hz);+ sky.addColorStop(0,'#1a0b2e');sky.addColorStop(.55,'#3d1152');sky.addColorStop(1,'#8a2160');+ ctx.fillStyle=sky;ctx.fillRect(0,0,W,hz);+ // glowing sun with retro scanline gaps+ const cx=W/2,cy=hz-6,rad=Math.min(W,H)*0.18;+ const sun=ctx.createLinearGradient(0,cy-rad,0,cy+rad);+ sun.addColorStop(0,'#ffe15a');sun.addColorStop(.5,'#ff8a3d');sun.addColorStop(1,'#ff2fb0');+ ctx.save();+ ctx.beginPath();ctx.arc(cx,cy,rad,Math.PI,0);ctx.closePath();ctx.clip();+ ctx.fillStyle=sun;ctx.fillRect(cx-rad,cy-rad,rad*2,rad*2);+ ctx.fillStyle='#1a0b2e';+ for(let i=0;i<7;i++){const y=cy-rad*.15+i*(rad*.16);ctx.fillRect(cx-rad,y+i*1.5,rad*2,Math.max(1,3-i*.3));}+ ctx.restore();+ // floor+ const flr=ctx.createLinearGradient(0,hz,0,H);+ flr.addColorStop(0,'#160726');flr.addColorStop(1,'#05010a');+ ctx.fillStyle=flr;ctx.fillRect(0,hz,W,H-hz);+}++function drawGrid(){+ const hz=horizon(),cx=W/2;+ ctx.strokeStyle=GLOW;ctx.shadowColor=GLOW;ctx.shadowBlur=8;ctx.lineWidth=1.4;+ // vertical lines converge to the vanishing point+ const cols=Math.round(DENS*0.7);+ for(let i=-cols;i<=cols;i++){+ const fx=cx+(i/cols)*W*1.4;+ ctx.beginPath();ctx.moveTo(cx,hz);ctx.lineTo(fx,H);ctx.stroke();+ }+ // horizontal lines: perspective spacing, scrolled by modulo offset+ for(let i=0;i<DENS;i++){+ let p=((i+offset)%DENS)/DENS; // 0 at horizon -> 1 at viewer, loops seamlessly+ const y=hz+Math.pow(p,2.2)*(H-hz);+ ctx.globalAlpha=Math.min(1,p*1.6);+ ctx.beginPath();ctx.moveTo(0,y);ctx.lineTo(W,y);ctx.stroke();+ }+ ctx.globalAlpha=1;ctx.shadowBlur=0;+}++function frame(){drawSky();drawGrid();}+function loop(ts){+ if(paused){raf=null;return;}+ raf=requestAnimationFrame(loop);+ const dt=ts-lastT;if(dt<16)return;lastT=ts;+ fpsEl.textContent=Math.round(1000/(dt||16))+' fps';+ offset+=SPD*0.02;frame();+}++resize();+if(reduce){frame();fpsEl.textContent='static';}+else raf=requestAnimationFrame(loop);+window.addEventListener('resize',()=>{resize();if(reduce)frame();});++document.getElementById('spd-sl').addEventListener('input',e=>{SPD=e.target.value/10;document.getElementById('spd-v').textContent=SPD.toFixed(1);});+document.getElementById('dens-sl').addEventListener('input',e=>{DENS=+e.target.value;document.getElementById('dens-v').textContent=DENS;if(reduce)frame();});+document.getElementById('glow-col').addEventListener('input',e=>{GLOW=e.target.value;document.getElementById('glow-hex').textContent=e.target.value;if(reduce)frame();});+document.getElementById('pause-btn').addEventListener('click',()=>{+ paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';+ if(!paused){lastT=performance.now();raf=requestAnimationFrame(loop);}+});+</script>+</body>+</html>diff --git a/index.html b/index.htmlindex 04fe8e0e..99c9e023 100644--- a/index.html+++ b/index.html@@ -61,6 +61,12 @@ main{position:relative;z-index:2;max-width:1200px;margin:0 auto;padding:clamp(24#q:focus{border-color:rgba(255,255,255,.28);background:#141418}.kbd{position:absolute;right:14px;font-size:10px;letter-spacing:.1em;color:var(--muted);border:1px solid var(--line);border-radius:3px;padding:3px 8px;transition:opacity .2s}#q:focus~.kbd,#q:not(:placeholder-shown)~.kbd{opacity:0}+.chips{display:flex;flex-wrap:wrap;gap:8px;margin-top:16px;max-width:840px}+.chip{min-height:44px;padding:8px 15px;border:1px solid var(--line);border-radius:100px;background:transparent;color:var(--ink-dim);+ font-family:var(--mono);font-size:11px;letter-spacing:.03em;cursor:pointer;transition:border-color .2s var(--ease),color .2s var(--ease),background .2s var(--ease)}+@media(hover:hover){.chip:hover{color:var(--ink);border-color:rgba(255,255,255,.26)}}+.chip:focus-visible{outline:none;border-color:var(--ink);box-shadow:0 0 0 2px rgba(255,255,255,.25)}+.chip.on{background:var(--ink);color:#0b0b0d;border-color:var(--ink)}.chapter{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:clamp(16px,3vw,30px);margin:clamp(60px,9vw,104px) 0 clamp(24px,3vw,36px);padding-bottom:20px;border-bottom:1px solid var(--line-2)}@@ -590,6 +596,50 @@ main{position:relative;z-index:2;max-width:1200px;margin:0 auto;padding:clamp(24.pv-aripple .s2 b{animation-duration:4.6s}@keyframes d-arip{0%{transform:translate(-50%,-50%) scale(1);opacity:.8}100%{transform:translate(-50%,-50%) scale(9);opacity:0}}+/* ── bespoke: added demos ── */+.pv-magnet{background:#08090c;display:grid;place-items:center;position:relative}+.pv-magnet .btn{padding:9px 20px;border-radius:6px;border:1px solid var(--accent);color:var(--accent);font-family:var(--mono);font-size:11px;animation:magbtn 3.6s var(--ease) infinite}+.pv-magnet .cur{position:absolute;width:8px;height:8px;border-radius:50%;background:var(--accent);animation:magcur 3.6s var(--ease) infinite}+@keyframes magbtn{0%,100%{transform:translate(0,0)}24%{transform:translate(15px,-9px)}56%{transform:translate(-13px,7px)}}+@keyframes magcur{0%,100%{transform:translate(34px,14px);opacity:0}14%{opacity:1}24%{transform:translate(24px,-12px)}56%{transform:translate(-22px,10px)}82%{opacity:1}92%{opacity:0}}+.pv-heart{background:#08090c;display:grid;place-items:center;position:relative}+.pv-heart .h{font-size:40px;line-height:1;color:var(--accent);animation:heartpop 2.8s var(--ease) infinite}+.pv-heart .p{position:absolute;width:5px;height:5px;border-radius:50%;background:var(--accent);opacity:0;animation:heartp 2.8s ease-out infinite}+.pv-heart .p:nth-child(2){--x:-28px;--y:-20px}.pv-heart .p:nth-child(3){--x:26px;--y:-22px}.pv-heart .p:nth-child(4){--x:-24px;--y:18px}.pv-heart .p:nth-child(5){--x:24px;--y:20px}.pv-heart .p:nth-child(6){--x:0px;--y:-30px}.pv-heart .p:nth-child(7){--x:0px;--y:28px}+@keyframes heartpop{0%,28%{transform:scale(.72)}42%{transform:scale(1.25)}56%,100%{transform:scale(1)}}+@keyframes heartp{0%,30%{transform:translate(0,0);opacity:0}42%{opacity:1}100%{transform:translate(var(--x,0),var(--y,0));opacity:0}}+.pv-confetti{background:#08090c;position:relative;overflow:hidden;display:grid;place-items:center}+.pv-confetti .btn{padding:8px 16px;border-radius:5px;background:var(--accent);color:#0b0b0d;font-size:10px;font-family:var(--mono)}+.pv-confetti i{position:absolute;top:52%;left:50%;width:6px;height:9px;border-radius:1px;opacity:0;animation:conf 2.6s ease-in infinite}+.pv-confetti i:nth-child(2){--x:-64px;background:var(--c1)}.pv-confetti i:nth-child(3){--x:-38px;background:var(--c3)}.pv-confetti i:nth-child(4){--x:-14px;background:var(--c2)}.pv-confetti i:nth-child(5){--x:14px;background:var(--c5)}.pv-confetti i:nth-child(6){--x:38px;background:var(--c7)}.pv-confetti i:nth-child(7){--x:64px;background:var(--c6)}+@keyframes conf{0%{transform:translate(-50%,0) rotate(0);opacity:0}14%{opacity:1}100%{transform:translate(calc(-50% + var(--x,0)),-62px) rotate(320deg);opacity:0}}+.pv-shake{background:#08090c;display:grid;place-items:center}+.pv-shake .field{width:58%;height:24%;border-radius:6px;border:1px solid #2a2e36;animation:shakef 3s infinite}+@keyframes shakef{0%,72%,100%{transform:translateX(0);border-color:#2a2e36}76%{transform:translateX(-7px);border-color:var(--accent)}80%{transform:translateX(6px)}84%{transform:translateX(-4px);border-color:var(--accent)}88%{transform:translateX(3px)}92%{transform:translateX(-1px)}}+.pv-swipe{background:#08090c;display:grid;place-items:center;padding:0 14%;position:relative}+.pv-swipe .del{position:absolute;left:14%;right:14%;height:28%;border-radius:6px;background:#c0392b}+.pv-swipe .crd{position:relative;width:100%;height:28%;border-radius:6px;background:#181c22;border:1px solid var(--line);animation:swipec 3.4s var(--ease) infinite}+@keyframes swipec{0%,18%{transform:translateX(0);opacity:1}52%{transform:translateX(70%);opacity:.7}68%,100%{transform:translateX(125%);opacity:0}}+.pv-glitch{background:#0c0608;display:grid;place-items:center;position:relative}+.pv-glitch .w{position:absolute;font-family:var(--disp);font-weight:800;font-size:32px;letter-spacing:-.02em}+.pv-glitch .base{color:var(--ink)}+.pv-glitch .r{color:#ff2d5e;mix-blend-mode:screen;animation:gl-r 1.8s steps(2,end) infinite}+.pv-glitch .cy{color:#2dffe6;mix-blend-mode:screen;animation:gl-cy 1.8s steps(2,end) infinite}+@keyframes gl-r{0%,100%{transform:translate(0,0);clip-path:inset(0 0 62% 0)}25%{transform:translate(-3px,-1px)}50%{transform:translate(2px,1px);clip-path:inset(52% 0 8% 0)}75%{transform:translate(-2px,2px);clip-path:inset(20% 0 40% 0)}}+@keyframes gl-cy{0%,100%{transform:translate(0,0);clip-path:inset(62% 0 0 0)}25%{transform:translate(3px,1px)}50%{transform:translate(-2px,-1px);clip-path:inset(8% 0 52% 0)}75%{transform:translate(2px,-2px);clip-path:inset(40% 0 20% 0)}}+.pv-onpath{background:#0c0608;display:grid;place-items:center}+.pv-onpath svg{width:92%;height:82%}+.pv-onpath text{fill:var(--accent);font-family:var(--disp);font-weight:700;font-size:11px;letter-spacing:.06em}+.pv-wavy{background:#0c0608;display:flex;align-items:center;justify-content:center}+.pv-wavy b{font-family:var(--disp);font-weight:800;font-size:30px;color:var(--accent);animation:wavyb 1.8s ease-in-out infinite}+.pv-wavy b:nth-child(2){animation-delay:.1s}.pv-wavy b:nth-child(3){animation-delay:.2s}.pv-wavy b:nth-child(4){animation-delay:.3s}.pv-wavy b:nth-child(5){animation-delay:.4s}+@keyframes wavyb{0%,100%{transform:translateY(22%)}50%{transform:translateY(-22%)}}+.pv-synth{background:linear-gradient(#160a2b,#33184f 46%,#0a0410);overflow:hidden;position:relative}+.pv-synth .sun{position:absolute;left:50%;top:36%;width:38%;aspect-ratio:1;border-radius:50%;transform:translate(-50%,-50%);background:linear-gradient(#ffd76a,#ff5f8b);filter:blur(.5px)}+.pv-synth .gr{position:absolute;left:-60%;right:-60%;bottom:-14%;height:58%;background-image:linear-gradient(color-mix(in srgb,var(--accent) 75%,transparent) 1px,transparent 1px),linear-gradient(90deg,color-mix(in srgb,var(--accent) 75%,transparent) 1px,transparent 1px);background-size:100% 20px,38px 100%;transform:perspective(120px) rotateX(64deg);transform-origin:bottom center;animation:synthg 1.1s linear infinite}+@keyframes synthg{to{background-position:0 20px,0 0}}+.pv-flow{background:#05060a}+@media(prefers-reduced-motion:reduce){.pv .anim{animation-play-state:paused!important}.card{transition:border-color .2s}@@ -610,9 +660,9 @@ main{position:relative;z-index:2;max-width:1200px;margin:0 auto;padding:clamp(24<header class="hero"><p class="kicker">Web animation reference</p><h1 class="wordmark">Animation<br>Handbook</h1>- <p class="lede">A reference of 100 web animation techniques. Every entry is a live demo you can open in the browser and read how it works.</p>+ <p class="lede">A reference of 113 web animation techniques. Every entry is a live demo you can open in the browser and read how it works.</p><div class="hero-foot">- <div class="stat"><b>100</b><span>Techniques</span></div>+ <div class="stat"><b>113</b><span>Techniques</span></div><div class="stat"><b>07</b><span>Categories</span></div><div class="stat"><b>0</b><span>Dependencies</span></div></div>@@ -621,6 +671,7 @@ main{position:relative;z-index:2;max-width:1200px;margin:0 auto;padding:clamp(24<input id="q" type="search" autocomplete="off" spellcheck="false" placeholder="Search techniques" aria-label="Search techniques"><span class="kbd" aria-hidden="true">/</span></div>+ <div class="chips" id="chips" role="group" aria-label="Filter by category"></div></header><div id="root"></div>@@ -667,6 +718,7 @@ const CATS=[['progress-bar','Progress Bar','Reading progress in three styles — top bar, circular ring, and side rail — driven by scrollTop / scrollHeight.'],['section-wipe','Section Wipe','The next section slides over the current via sticky z-index stacking — scale-down adds depth.'],['zoom-into-image','Zoom Into Image','clip-path expands from a framed card to full-bleed as you scroll — the portal effect.'],+ ['scroll-image-sequence','Scroll Image Sequence','A canvas pinned with sticky; scroll progress maps to a frame index — the Apple product-scroll technique, frames drawn procedurally.'],]},{@@ -717,7 +769,10 @@ const CATS=[['click-ripple','Click / Tap Ripple','Ripple emanates from the exact click point — Material Design\'s tactile confirmation pattern.'],['focus-ring','Focus Ring Animation','Animated outline on keyboard Tab — :focus-visible ensures mouse users see no ring.'],['button-press-scale','Button Press Scale','Scales to 0.95 on press, springs back on release — asymmetric timing gives a tactile feel.'],+ ['magnetic-button','Magnetic Button','Button leans toward the cursor within a radius, label lagging for parallax — springs home on exit.'],['toggle-switch','Toggle / Switch Slide','Pill slides left/right for on/off — smooth cubic-bezier gives a weighted, physical feel.'],+ ['heart-burst','Heart / Like Burst','Tap pops and fills the heart while small hearts burst outward on canvas — Twitter-style like.'],+ ['success-confetti','Success Confetti','Completing an action fires a canvas confetti burst — rotating rectangles with gravity and spin.'],['skeleton-loader','Skeleton Loader','Pulsing placeholder blocks match the shape of real content — reduces perceived wait time.'],['shimmer-effect','Shimmer Effect','Gradient sweep over skeleton placeholders — gives the impression of data streaming in.'],['loading-spinner','Loading Spinner','Six spinner variants from a single CSS color and speed — ring, orbit, arc, bounce, pulse, square.'],@@ -730,6 +785,8 @@ const CATS=[['modal-expand','Modal Expand','Modal scales from the trigger button\'s position — transform-origin set to where you clicked.'],['accordion','Accordion Open/Close','Height animates between 0 and auto — JS measured height vs CSS grid-template-rows compared.'],['cursor-follower','Cursor Follower','Custom element follows mouse with lerp lag — mix-blend-mode: difference inverts any background.'],+ ['error-shake','Error Shake','An invalid field shakes horizontally with a decaying wobble and flashes red — the universal "no".'],+ ['swipe-to-dismiss','Swipe to Dismiss','Drag a card past a threshold and it flies off as the row collapses — pointer-driven, touch-ready.'],]},{@@ -748,6 +805,9 @@ const CATS=[['outline-to-fill','Outline to Fill','Hollow stroke letterforms fill with color — clip-path reveal or opacity crossfade.'],['enter-exit-typography','Enter/Exit Typography','Three-act phrase lifecycle: enter → hold → exit, sequenced for storytelling.'],['rotate-word-carousel','Rotate Word Carousel','One keyword cycles through a list while the surrounding sentence stays static.'],+ ['glitch-text','Glitch Text','RGB-split copies jitter behind animated clip-path slices — the datamosh / signal-loss aesthetic.'],+ ['text-on-path','Text on a Path','Text flows along an SVG curve via textPath with an animated startOffset — wave, arc, or circle.'],+ ['wavy-text','Wavy Text','Per-letter sine-wave bob with a staggered delay sends a wave travelling across the word.'],]},{@@ -771,6 +831,7 @@ const CATS=[['image-distortion-hover','Image Distortion on Hover','Fragment shader displaces UV coordinates around the cursor — ripple, push, liquid, pixelate.'],['cloth-simulation','Cloth Simulation','Verlet integration + distance constraints — draggable flag responds to gravity and wind.'],['volumetric-smoke','Volumetric Smoke','Ray marching accumulates 3D noise density — light scattering, shadow rays, fBm clouds.'],+ ['morphing-blob','Morphing Blob','Metaball circles fused by an SVG blur-plus-contrast filter melt like liquid — the blob drifts and a droplet chases the pointer.'],]},{@@ -790,6 +851,9 @@ const CATS=[['floating-elements','Floating Elements','Geometric shapes drift on independent sine-wave paths — no two elements synchronized.'],['grid-dot-pattern-parallax','Grid / Dot Pattern Parallax','Pattern shifts subtly opposite to mouse movement — depth felt, barely seen.'],['abstract-geometric-motion','Abstract Geometric Motion','Four hypnotic loops: rotating polygons, expanding rings, sliding bars, flowing color lines.'],+ ['particle-constellation','Particle Constellation','Drifting nodes link with lines when they come close — the network-mesh hero background.'],+ ['flow-field','Flow Field','Particles follow a noise-driven vector field, leaving flowing trails.'],+ ['synthwave-grid','Synthwave Grid','A perspective grid scrolls toward a glowing sun — the retro synthwave horizon.'],]}];@@ -799,7 +863,7 @@ const PV={'cover-card-to-fixed-header':'cover','fly-in-fly-out-contact-list':'flylist','stacking-cards':'stack','scroll-trigger':'trigger','scrub-animation':'scrub','pin-animation':'pin','snap-scrolling':'snap','scrollytelling':'story','reveal-on-scroll':'reveal','stagger-reveal':'stagger','horizontal-scroll':'hscroll',- 'sticky-section':'sticky','counter-animation':'counter','progress-bar':'progress','section-wipe':'wipe','zoom-into-image':'zoom',+ 'sticky-section':'sticky','counter-animation':'counter','progress-bar':'progress','section-wipe':'wipe','zoom-into-image':'zoom','scroll-image-sequence':'scrub','fade-in-out':'fade','slide-in':'slidein','slide-up-reveal':'slideup','scale-in':'scalein','clip-path-reveal':'clipreveal','curtain-reveal':'curtain','split-text-reveal':'split','letter-by-letter-stagger':'letters','word-by-word-reveal':'words','blur-in':'blurin',@@ -819,11 +883,14 @@ const PV={'canvas-particle-effect':'particles','fluid-simulation':'fluid','glassmorphism-animated':'glass','webgl-shader-animation':'shader','noise-based-motion':'noiseblob','svg-path-animation':'svgpath','chromatic-aberration':'chroma','2-5d-pseudo-3d':'pseudo3d','ray-marching-sdf':'raymarch',- 'gpgpu-particle-system':'gpgpu','image-distortion-hover':'distort','cloth-simulation':'cloth','volumetric-smoke':'smoke',+ 'gpgpu-particle-system':'gpgpu','image-distortion-hover':'distort','cloth-simulation':'cloth','volumetric-smoke':'smoke','morphing-blob':'mesh','animated-gradient-background':'mesh','mesh-gradient':'mesh','aurora':'aurora','starfield':'starfield','breathing-glow':'glow','ambient-ripple':'aripple','grain-overlay':'grain2','scanline':'scan','light-leak':'leak','floating-elements':'floaters',- 'grid-dot-pattern-parallax':'dotgrid','abstract-geometric-motion':'geo'+ 'grid-dot-pattern-parallax':'dotgrid','abstract-geometric-motion':'geo',+ 'magnetic-button':'magnet','heart-burst':'heart','success-confetti':'confetti','error-shake':'shake','swipe-to-dismiss':'swipe',+ 'glitch-text':'glitch','text-on-path':'onpath','wavy-text':'wavy',+ 'particle-constellation':'particles','flow-field':'flow','synthwave-grid':'synth'};function pvMarkup(k){@@ -932,6 +999,16 @@ function pvMarkup(k){case 'dotgrid': return '<span class="dots anim"></span>';case 'geo': return '<span class="ring r2 anim"></span><span class="ring r1 anim"></span><span class="poly anim"></span>';case 'aripple': return '<span class="src s1"><b class="anim"></b><b class="anim"></b><b class="anim"></b></span><span class="src s2"><b class="anim"></b><b class="anim"></b><b class="anim"></b></span>';+ case 'magnet': return '<span class="btn anim">Magnetic</span><span class="cur anim"></span>';+ case 'heart': return '<span class="h anim">♥</span>'+'<span class="p anim"></span>'.repeat(6);+ case 'confetti': return '<span class="btn">Done</span>'+'<i class="anim"></i>'.repeat(6);+ case 'shake': return '<span class="field anim"></span>';+ case 'swipe': return '<span class="del"></span><span class="crd anim"></span>';+ case 'glitch': return '<span class="w base">GLITCH</span><span class="w r anim">GLITCH</span><span class="w cy anim">GLITCH</span>';+ case 'onpath': return '<svg viewBox="0 0 240 96"><path id="opG" d="M12 64 Q 66 14 122 50 T 232 34" fill="none" stroke="rgba(255,255,255,.14)" stroke-width="1.5"/><text><textPath href="#opG" startOffset="0"><animate attributeName="startOffset" values="0;150" dur="7s" repeatCount="indefinite"/>ANIMATION · HANDBOOK · </textPath></text></svg>';+ case 'wavy': return 'WAVES'.split('').map(function(c){return '<b class="anim">'+c+'</b>';}).join('');+ case 'synth': return '<span class="sun"></span><span class="gr anim"></span>';+ case 'flow': return '';default: return '';}}@@ -1005,7 +1082,21 @@ function particlesFactory(pv,count,connect){size();addEventListener('resize',size);return {play(){if(!raf&&!reduce)frame();},pause(){if(raf){cancelAnimationFrame(raf);raf=null;}}};}-const engines={starfield,scramble,counter,particles:pv=>particlesFactory(pv,46,true),gpgpu:pv=>particlesFactory(pv,150,false)};+function flowEngine(pv){+ const c=document.createElement('canvas');pv.appendChild(c);const ctx=c.getContext('2d');+ let w,h,ps,raf=null;const D=devicePixelRatio;+ function ang(x,y){return (Math.sin(x*0.9+y*0.6)+Math.cos(y*1.1-x*0.5))*Math.PI;}+ function size(){const r=pv.getBoundingClientRect();w=c.width=r.width*D;h=c.height=r.height*D;+ ps=Array.from({length:55},()=>({x:Math.random()*w,y:Math.random()*h}));ctx.fillStyle='#05060a';ctx.fillRect(0,0,w,h);}+ function draw(){ctx.fillStyle='rgba(5,6,10,.09)';ctx.fillRect(0,0,w,h);ctx.fillStyle='rgba(95,216,138,.85)';+ for(const p of ps){const a=ang(p.x/(70*D),p.y/(70*D));p.x+=Math.cos(a)*1.2*D;p.y+=Math.sin(a)*1.2*D;+ if(p.x<0||p.x>w||p.y<0||p.y>h){p.x=Math.random()*w;p.y=Math.random()*h;}+ ctx.fillRect(p.x,p.y,1.5*D,1.5*D);}}+ function frame(){draw();raf=requestAnimationFrame(frame);}+ size();addEventListener('resize',size);+ return {play(){if(!raf&&!reduce)frame();},pause(){if(raf){cancelAnimationFrame(raf);raf=null;}}};+}+const engines={starfield,scramble,counter,particles:pv=>particlesFactory(pv,46,true),gpgpu:pv=>particlesFactory(pv,150,false),flow:flowEngine};document.querySelectorAll('.card').forEach(card=>{const pv=card.querySelector('.pv'),type=card.dataset.pv;@@ -1014,6 +1105,7 @@ document.querySelectorAll('.card').forEach(card=>{card._pause=()=>{card.classList.remove('playing');eng&&eng.pause();};card.addEventListener('focus',card._play);});+if(reduce)document.querySelectorAll('.pv animate').forEach(a=>a.remove());const hoverCap=matchMedia('(hover:hover)').matches;if('IntersectionObserver'in window){const io=new IntersectionObserver(es=>es.forEach(e=>{e.target[e.isIntersecting?'_play':'_pause']();}),@@ -1023,11 +1115,23 @@ if('IntersectionObserver'in window){const q=document.getElementById('q'),emptyEl=document.getElementById('empty'),sections=[...document.querySelectorAll('.cat')];const cards=[...document.querySelectorAll('.card')];cards.forEach(c=>c._t=c.textContent.toLowerCase());-q.addEventListener('input',()=>{+let activeCat='all';+function applyFilter(){const term=q.value.trim().toLowerCase();let shown=0;- sections.forEach(s=>{let vis=0;s.querySelectorAll('.card').forEach(c=>{const m=!term||c._t.includes(term);c.style.display=m?'':'none';if(m){vis++;shown++;}});s.hidden=vis===0;});+ sections.forEach(s=>{const catOk=activeCat==='all'||s.classList.contains(activeCat);let vis=0;+ s.querySelectorAll('.card').forEach(c=>{const m=catOk&&(!term||c._t.includes(term));c.style.display=m?'':'none';if(m){vis++;shown++;}});+ s.hidden=vis===0;});emptyEl.classList.toggle('show',shown===0);-});+}+q.addEventListener('input',applyFilter);+const chipBar=document.getElementById('chips');+if(chipBar){+ const mk=(label,cat)=>{const b=document.createElement('button');b.type='button';b.className='chip'+(cat==='all'?' on':'');b.textContent=label;b.dataset.cat=cat;chipBar.appendChild(b);};+ mk('All','all');CATS.forEach(c=>mk(c.name,c.cat.replace('-cat','')));+ chipBar.addEventListener('click',e=>{const b=e.target.closest('.chip');if(!b)return;+ activeCat=b.dataset.cat;chipBar.querySelectorAll('.chip').forEach(x=>x.classList.toggle('on',x===b));applyFilter();+ if(activeCat!=='all'){const sec=sections.find(s=>s.classList.contains(activeCat));if(sec)sec.scrollIntoView({behavior:reduce?'auto':'smooth',block:'start'});}});+}addEventListener('keydown',e=>{const t=document.activeElement.tagName;if(e.key==='/'&&document.activeElement!==q&&t!=='INPUT'){e.preventDefault();q.focus();}else if(e.key==='Escape'&&document.activeElement===q){q.value='';q.dispatchEvent(new Event('input'));q.blur();}});