Motion implementation guide
How to build the interaction families seen in the catalogue (
Micro interaction,Morphing,Hover effect,Scroll animation,Page transition,Drag interaction,Reveal,Loading animation,Physics,Rive,Interactive 3D,Sound design...) with CSS, WAAPI, the View Transitions API, motion.dev (Framer Motion), GSAP + ScrollTrigger, Lenis, Rive, Lottie and Three.js. The catalogue shows outcomes, not source: library choices are[inferred]from tags and descriptions (explicit tool mentions: Rive 20 designs, Three.js/WebGL in carousels such as 01M4ARCHC… and 01M4AR8FR…, SwiftUI for 01M4FJWC5…, Locomotive Scroll for 01M4T8V5H…). Durations/easings quoteinteraction-principles.mdand pattern IDs come frominteraction-patterns.md. Verify API availability against current docs when targeting older browsers.
0. Which tool for which pattern
| Pattern (see interaction-patterns.md) | Best tool | Why |
|---|---|---|
| Hover/press/focus state, toggles, tooltip in/out | CSS transitions (+ @starting-style) |
zero JS, compositor friendly |
| Spring-feel with no JS | CSS linear() easing |
pre-sampled spring curve |
| Pill-to-panel morph, spring indicator, reorder, shared layout | motion.dev layout/layoutId (React) or FLIP with WAAPI |
measures and animates via transforms |
| Route / list-to-detail shared-element transition | View Transitions API | browser snapshots, cross-document support |
| Sequencing 3+ steps with precise offsets (dock squeeze -> expand -> items) | WAAPI timeline or GSAP timeline or Motion animate sequences |
explicit time offsets |
| Scroll-linked scenes, pinned stacks, 3D scrub | CSS scroll-driven animations (simple) or GSAP ScrollTrigger (complex) | animation-timeline / scrub |
| Smooth scroll inertia | Lenis (sync with GSAP ticker) | lerped scroll position |
| Interactive mascots, state-machine vector UI | Rive | inputs + state machines, 60 fps vector |
| Pre-rendered illustration/loader | Lottie / dotLottie | AE export, play/segments |
| Particles, 3D, shader backgrounds, refractive glass | Three.js / R3F / OGL / raw WebGL | GPU |
| Confetti | canvas-confetti |
tiny, one-shot |
| UI sounds | Web Audio API (+ small samples) | latency |
1. Ground rules that apply everywhere
- Compositor-only properties: animate
transform(translate/scale/rotate),opacity, and (with care)filter,clip-path. Express size changes asscaleor FLIP; never tweenwidth/height/top/left/marginin hot paths. The catalogue's ~0.3 s morphs animatewidth/heightvisibly, but production builds should convert via FLIP/layout animation. - Durations by role (from
interaction-principles.md): tiny feedback 120-220 ms; hover/state 250-450 ms; morph/panel 300-450 ms; exit = 0.7 x enter; page 500-900 ms; entrance sequence total 1.0-2.6 s; stagger gap 60-130 ms (cap group at ~1.2 s). - Default easing: expo/quint ease-out. Tokens:
:root{
--ease-out: cubic-bezier(0.22, 1, 0.36, 1); /* most morphs, hovers, entrances */
--ease-in-out: cubic-bezier(0.65, 0, 0.35, 1); /* reveals, scroll scenes, carousels */
--ease-in: cubic-bezier(0.5, 0, 0.75, 0); /* exits that leave the screen */
--t-fast: 150ms; --t-base: 300ms; --t-slow: 500ms;
}
- Spring via CSS (no JS):
linear()with a sampled spring; slight overshoot ~3-8% (functional) or ~15% (playful):
:root{ --spring-soft: linear(0, 0.12 6%, 0.46 14%, 0.78 24%, 1.02 38%, 1.06 46%, 1.03 58%, 0.995 72%, 1); } /* ~5% overshoot [inferred values; regenerate with a linear() spring generator] */
.pill{ transition: transform 450ms var(--spring-soft), opacity 200ms linear; }
- Interruptibility: every transition must be reversible mid-flight (CSS transitions do this; WAAPI via
animation.reverse(); Motion springs preserve velocity). - Reduced motion (section 10) and focus parity: every
:hovereffect also on:focus-visible. - Do not animate on first paint what is the LCP; cap start delay for headline to ~100-300 ms.
- Source clips are 30 fps; build for 60+ fps; a state change <= 2 frames (~66 ms) at 30 fps is effectively a swap: do not add 400 ms where the clip shows an instant flip (e.g. color flips on the run-code chip 01M4ZATZ3…).
2. CSS building blocks
Transitions and entry/exit with @starting-style
.menu{ opacity:0; transform: translateY(8px) scale(.98); transition: opacity 200ms var(--ease-out), transform 300ms var(--ease-out), display 300ms allow-discrete; display:none; }
.menu[open]{ display:block; opacity:1; transform:none; }
@starting-style{ .menu[open]{ opacity:0; transform: translateY(8px) scale(.98); } }
(transition-behavior: allow-discrete / display transitions and @starting-style are modern-browser features; keep an animation-based fallback if you must support older engines.)
Keyframes for loops (shimmer, dots, pulses)
@keyframes shimmer{ to{ background-position: -200% 0; } }
.skeleton{ background: linear-gradient(90deg,#eee 25%,#f7f7f7 37%,#eee 63%); background-size:200% 100%; animation: shimmer 1.4s linear infinite; border-radius:12px; }
@keyframes pulse{ 50%{ opacity:.45; } }
Skeleton shimmer 1.2-1.6 s linear loops; AI image placeholders in the catalogue run ~5 s before resolving 01M4FMPPZ….
Scroll-driven animations (CSS)
@keyframes reveal{ from{ opacity:0; transform: translateY(24px);} to{ opacity:1; transform:none; } }
.card{ animation: reveal linear both; animation-timeline: view(); animation-range: entry 0% entry 40%; }
.progress{ transform-origin:0 50%; animation: grow linear; animation-timeline: scroll(root); }
@keyframes grow{ from{ transform: scaleX(0);} to{ transform: scaleX(1);} }
@supports not (animation-timeline: view()){ /* fallback: IntersectionObserver adds .in-view with the same keyframes */ }
Use for reveals and progress bars (Scroll animation 1,255). Use GSAP when you need pinning, snapping or timelines across elements.
Number and color interpolation with @property
@property --n{ syntax:'<integer>'; inherits:false; initial-value:0; }
.count{ counter-reset: num var(--n); transition: --n 800ms var(--ease-out); }
.count::after{ content: counter(num); font-variant-numeric: tabular-nums; }
.count.go{ --n: 24983; }
Good for simple tickers; for odometer digit columns use transforms (section 9).
3. Web Animations API (WAAPI)
const a = el.animate(
[{ transform: 'scale(.96)', opacity: 0, filter: 'blur(6px)' }, { transform: 'none', opacity: 1, filter: 'blur(0)' }],
{ duration: 450, easing: 'cubic-bezier(.22,1,.36,1)', fill: 'both' });
await a.finished;
a.commitStyles(); a.cancel(); // persist end state as inline style
- Sequence with explicit offsets (dock: collapse 70 ms, hold 70 ms, expand 170 ms, items +40 ms each 01M4QJJF6…):
const dock = document.querySelector('.dock'), items = dock.querySelectorAll('.row');
const t = {collapse:70, hold:70, expand:170}, total = t.collapse+t.hold+t.expand;
dock.animate([
{width:'110px',height:'25px',borderRadius:'999px',offset:0},
{width:'96px',height:'14px',offset:t.collapse/total}, // anticipation squeeze
{width:'96px',height:'14px',offset:(t.collapse+t.hold)/total}, // hold
{width:'130px',height:'106px',borderRadius:'14px',offset:1}], // expand
{duration:total, easing:'cubic-bezier(.22,1,.36,1)', fill:'forwards'});
items.forEach((r,i)=>r.animate([{opacity:0,transform:'translateY(6px)'},{opacity:1,transform:'none'}],
{delay:t.collapse+t.hold+t.expand*0.6+i*45, duration:180, easing:'ease-out', fill:'backwards'}));
(Width/height here for clarity; for production use FLIP or a transform: scale with counter-scaled children.)
- FLIP helper: measure first rect, change DOM, measure last rect, animate the inverse transform.
4. View Transitions API
Same-document (SPA) list -> detail with shared element (cf. note app zoom 01M4X16WZ…, card claim 01M4ZBKV5…):
function go(update){ if(!document.startViewTransition) return update(); return document.startViewTransition(update); }
.card.active .thumb{ view-transition-name: hero; }
.detail .hero{ view-transition-name: hero; }
::view-transition-group(hero){ animation-duration: 450ms; animation-timing-function: cubic-bezier(.22,1,.36,1); }
::view-transition-old(root){ animation: 250ms ease both fade-out, 450ms ease both scale-down; } /* backdrop recede ~0.96 + dim */
::view-transition-new(root){ animation: 350ms 100ms ease both fade-in; }
@media (prefers-reduced-motion: reduce){ ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*){ animation: none; } }
Cross-document (MPA, portfolio route transitions like 01M4FNJBB…): @view-transition{ navigation: auto; } in both pages, name matching elements with view-transition-name (unique per page). Add view-transition-class for grouped styling. Always feature-detect; the fallback is an instant swap.
5. motion.dev / Framer Motion (React)
Install motion, import from motion/react.
Pill-to-panel morph with shared layout
import { motion, AnimatePresence } from 'motion/react'
const spring = { type:'spring', stiffness: 380, damping: 32, mass: 1 } // [inferred] ~300 ms, ≤3% overshoot
<motion.div layout style={{ borderRadius: open ? 24 : 999 }} transition={spring}
className="bg-black text-white overflow-hidden" onClick={()=>setOpen(o=>!o)}>
<motion.div layout="position">{open ? <Panel/> : <Pill/>}</motion.div>
</motion.div>
Notes: set borderRadius via style so layout animations correct distortion; fade content with AnimatePresence mode="popLayout" and 150 ms opacity + 4-6 px blur; closing uses a shorter spring (stiffness 500, damping 38) to hit ~0.7x.
Indicator dot / underline
{items.map(i => <li key={i.id} onClick={()=>setActive(i.id)}>
{active===i.id && <motion.span layoutId="dot" transition={{type:'spring',stiffness:500,damping:30}} className="dot"/>}
{i.label}</li>)}
Bouncy variant damping 14-20 for playful docks and mascots 01M4G5J98… 01M4XMHEH….
Stagger entrance (hero words/cards)
const container = { hidden:{}, show:{ transition:{ staggerChildren:.11, delayChildren:.15 } } }
const word = { hidden:{ opacity:0, y:16, filter:'blur(6px)' }, show:{ opacity:1, y:0, filter:'blur(0px)', transition:{ duration:.45, ease:[.22,1,.36,1] } } }
<motion.h1 variants={container} initial="hidden" animate="show">
{text.split(' ').map((w,i)=><motion.span key={i} variants={word} style={{display:'inline-block'}}>{w} </motion.span>)}
</motion.h1>
Values mirror 01M4G3XWH… (word gap ~100-130 ms). Cards: staggerChildren: .1, scale .96 -> 1, y 24 -> 0 01M4ZCSY0….
Drag, reorder, card stack
import { Reorder } from 'motion/react'
<Reorder.Group axis="y" values={items} onReorder={setItems}>
{items.map(it=><Reorder.Item key={it.id} value={it} whileDrag={{ scale:1.03, boxShadow:'0 12px 28px rgba(0,0,0,.18)' }}
transition={{ type:'spring', stiffness:500, damping:35 }}>{it.label}</Reorder.Item>)}
</Reorder.Group>
Card flick:
<motion.div drag="x" dragSnapToOrigin dragElastic={0.2}
style={{ x, rotate: useTransform(x, [-200,200], [-18,18]) }}
onDragEnd={(_,info)=>{ if (Math.abs(info.offset.x) > 100 || Math.abs(info.velocity.x) > 500) dismiss(info.offset.x > 0 ? 1 : -1) }} />
// dismiss: animate(x, ±window.innerWidth, { type:'tween', duration:.4, ease:[.22,1,.36,1] }); next card: scale .95 -> 1, y 12 -> 0, ~250 ms
(Reference gestures: 01M4QKQ2M… 01M4Y9Q7N….)
Scroll-linked values
const { scrollYProgress } = useScroll({ target: ref, offset: ['start end','end start'] })
const y = useTransform(scrollYProgress, [0,1], ['10%','-10%']) // parallax 0.1-0.4 factor
const smooth = useSpring(scrollYProgress, { stiffness: 120, damping: 30, mass: .3 })
Number ticker (motion value)
const mv = useMotionValue(0); const text = useTransform(mv, v => Math.round(v).toLocaleString())
useEffect(()=>{ const c = animate(mv, value, { duration:.8, ease:[.22,1,.36,1] }); return c.stop }, [value])
<motion.span className="tabular-nums">{text}</motion.span>
Matches the ~0.8 s ticker in 01M4XK0DK…. For a digit-column odometer translate a 0-9 stack by -digit * 1em with per-digit delay i*40ms.
Reduced motion globally
<MotionConfig reducedMotion="user"> turns transform/layout animation into opacity-only when the OS requests it.
6. GSAP + ScrollTrigger (+ Lenis)
import gsap from 'gsap'; import { ScrollTrigger } from 'gsap/ScrollTrigger'; import Lenis from 'lenis'
gsap.registerPlugin(ScrollTrigger)
const lenis = new Lenis({ lerp: 0.1, smoothWheel: true }) // lerp ~0.08-0.12 matches the "smooth scroll" clips
lenis.on('scroll', ScrollTrigger.update)
gsap.ticker.add(t => lenis.raf(t * 1000)); gsap.ticker.lagSmoothing(0)
// pinned accordion stack (cf. [01M4XXXCRQ9Z5TRZJSAHCV9FRS])
const tl = gsap.timeline({ scrollTrigger:{ trigger:'.process', start:'top top', end:'+=300%', pin:true, scrub:0.6 } })
cards.forEach((c,i)=> tl.to(c, { flexGrow: 6, duration: 1, ease:'power2.inOut' }, i))
// headline entrance, lines 0.15-0.3 s apart (cf. [01M50YSGQFYZ4F2Z8CSQWFCS50])
gsap.from('.hero .line', { yPercent:100, opacity:0, duration:.7, ease:'expo.out', stagger:.2 })
scrub: truelocks to the scroll;scrub: 0.5-1adds the lag seen in premium scroll sites. Usegsap.matchMedia()to branch desktop/mobile/reduced-motion.- SplitText for word/line staggers; Flip plugin for FLIP; MorphSVG (or flubber) for path morphs such as the wiggle slider scribble -> line 01M4Z4HP6…; CustomEase for bespoke curves. GSAP plugins are free to use [verify current license on gsap.com].
- Video/canvas scroll scrubbing: pre-extract frames to an image sequence or encode with frequent keyframes; update
video.currentTimein arequestAnimationFrameloop, not on each scroll event (01M4Z6QP5…). - Preloader:
gsap.timeline()counter ->clip-path: inset(0 0 100% 0)wipe (~800 mspower3.inOut) -> hero stagger 01M50SQTM….
7. Pattern sketches (framework-agnostic)
Button state machine (idle -> busy -> success)
async function run(btn, task){
btn.dataset.state='busy'; btn.setAttribute('aria-busy','true');
try{ await task(); btn.dataset.state='success'; } catch{ btn.dataset.state='error'; }
setTimeout(()=>{ btn.dataset.state='idle'; btn.removeAttribute('aria-busy') }, 1500);
}
.btn{ min-width:44px; height:44px; border-radius:999px; transition: width 280ms var(--ease-out), background-color 100ms linear; }
.btn[data-state=busy]{ width:44px; background:#111; } /* collapses to spinner circle */
.btn[data-state=success]{ background:#22c55e; } /* green flips in ~100 ms */
.btn[data-state=error]{ animation: shake 350ms; }
@keyframes shake{ 20%,60%{ transform: translateX(-6px);} 40%,80%{ transform: translateX(6px);} }
Use interpolate-size: allow-keywords or explicit pixel widths measured via JS; pair with an aria-live region.
SVG check draw + ring pop
.check path{ stroke-dasharray: 24; stroke-dashoffset: 24; animation: draw 400ms 120ms var(--ease-out) forwards; }
@keyframes draw{ to{ stroke-dashoffset: 0; } }
.ring{ animation: pop 450ms var(--spring-soft) both; } @keyframes pop{ from{ transform: scale(.8); opacity:0 } }
Edge-glow success sweep (dark phone frame)
A conic-gradient border animated with @property --angle:
@property --angle{ syntax:'<angle>'; inherits:false; initial-value:0deg; }
.glow{ border:2px solid transparent; background: linear-gradient(#000,#000) padding-box, conic-gradient(from var(--angle), #7c3aed, #38bdf8, #22d3ee, #7c3aed) border-box; animation: spin 1s var(--ease-out) forwards; }
@keyframes spin{ to{ --angle: 360deg; } }
(approximates 01M7WQW4J…).
Magnetic pill
const lerp=(a,b,t)=>a+(b-a)*t; let tx=0,ty=0,x=0,y=0, raf;
el.addEventListener('pointermove',e=>{ const r=el.getBoundingClientRect(); tx=(e.clientX-(r.left+r.width/2))*.3; ty=(e.clientY-(r.top+r.height/2))*.3; loop() });
el.addEventListener('pointerleave',()=>{ tx=ty=0; loop() });
function loop(){ cancelAnimationFrame(raf); (function f(){ x=lerp(x,tx,.15); y=lerp(y,ty,.15); el.style.transform=`translate3d(${x}px,${y}px,0)`; if(Math.abs(x-tx)+Math.abs(y-ty)>.1) raf=requestAnimationFrame(f) })() }
Wrap in matchMedia('(pointer:fine)'). For cursor followers use pointermove + translate3d + mix-blend-mode:difference, 10-14 px dot, grow to ~40 px over interactive targets (01M4FYM28…, 01M4YZA98…).
Dock magnification
dock.addEventListener('pointermove',e=>{ icons.forEach(i=>{ const c=i.getBoundingClientRect(); const d=Math.abs(e.clientX-(c.left+c.width/2)); const s=1+0.4*Math.exp(-(d*d)/(2*110*110)); i.style.setProperty('--s', s) }) })
// .icon{ transform: scale(var(--s,1)); transition: transform 120ms linear; transform-origin: 50% 100% }
(CSS springs or Motion useSpring per icon gives the overshoot seen in 01M4XMHEH….)
Goo (metaball) pull-to-refresh
<svg width="0" height="0"><filter id="goo"><feGaussianBlur in="SourceGraphic" stdDeviation="9"/><feColorMatrix values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 18 -7"/></filter></svg>
<div style="filter:url(#goo)"><div class="island"></div><div class="drop" style="transform:translateY(var(--pull))"></div></div>
Drive --pull from touch delta (rubber-band: pull = max * (1 - exp(-delta/max))), release with spring (bounce ~0.2) 01M7W98MN…. Keep filtered region small.
Mosaic dissolve / pixel transition
Render image into a grid of N x M tiles (CSS grid + background-position) or canvas; set per-tile transition-delay: random*0.5s, opacity 0->1 over 150-250 ms; total 0.5-0.9 s. WebGL variant: fragment shader step(noise(uv*grid), progress) (01M4YYZN8…, 01M4VK52R…).
Confetti
import confetti from 'canvas-confetti'
const r = el.getBoundingClientRect()
confetti({ particleCount: 50, spread: 70, startVelocity: 35, gravity: 1.1, ticks: 120,
origin: { x:(r.left+r.width/2)/innerWidth, y:(r.top+r.height/2)/innerHeight }, disableForReducedMotion: true })
UI sound
const ctx = new (window.AudioContext||window.webkitAudioContext)()
function tick(freq=880){ const o=ctx.createOscillator(), g=ctx.createGain(); o.type='sine'; o.frequency.value=freq; g.gain.setValueAtTime(0,ctx.currentTime); g.gain.linearRampToValueAtTime(.08,ctx.currentTime+.008); g.gain.exponentialRampToValueAtTime(.0001,ctx.currentTime+.14); o.connect(g).connect(ctx.destination); o.start(); o.stop(ctx.currentTime+.15) }
Create the context from a user gesture; add a persistent mute toggle (01M4Z1QMN…, 01M4XFC9H…).
Real-time cursors
// on socket 'cursor' message: target = {x,y}; each frame: pos += (target-pos)*0.2
Name tag 11-12 px in a pill of the cursor hue; hide after ~4 s idle (01M4ZTYRX…).
8. Rive and Lottie
- Rive (
Rivetag, 20): design in the Rive editor with a State Machine and inputs (Boolean isHover,Number progress,Trigger click). Runtime:@rive-app/react-canvas:
import { useRive, useStateMachineInput } from '@rive-app/react-canvas'
const { rive, RiveComponent } = useRive({ src:'/mascot.riv', stateMachines:'main', autoplay:true })
const look = useStateMachineInput(rive,'main','lookX') // 0..100 mapped from pointer x
<RiveComponent onMouseMove={e=>{ if(look) look.value = e.nativeEvent.offsetX / e.currentTarget.clientWidth * 100 }} />
Use for mascots 01M4XGCSE…, dice buttons 01M4X7YDF…, expressive sliders 01M4Z4HP6… 01M4Z06AV…. Transition blends ~150-250 ms. Pause when off-screen.
- Lottie (only 1 tagged design; still the standard export for After Effects loaders): @lottiefiles/dotlottie-web or lottie-react; play segments for state changes (idle loop -> success segment), set renderer: 'svg' for crisp small UI, 'canvas' for heavy files; keep JSON < ~100 KB [inferred]. Prefer Rive for interactive input-driven motion.
9. Three.js / WebGL for Interactive 3D and floating elements
- Stack: Three.js (or React Three Fiber + drei), OGL for minimal shader quads. Typical catalogue use: rotating glass prism carousels, jelly/refractive cards, 3D hero ribbons, particle fields.
renderer.setPixelRatio(Math.min(devicePixelRatio, 2))
renderer.setAnimationLoop(t => { uniforms.uTime.value = t*0.001; uniforms.uMouse.value.lerp(target, 0.08); renderer.render(scene, camera) })
- Pointer follow with lerp 0.05-0.1; drag inertia: on release continue
vel *= 0.95per frame; spring camera moves. - Scroll-driven camera: GSAP ScrollTrigger
scrub:1updatingcamera.positionor a model rotation. - Refractive glass:
MeshTransmissionMaterial(drei) withthickness,chromaticAberration ~0.02-0.08; it is expensive: cap DPR, number of transmissive meshes (<= 5-10 on desktop), and provide a static poster on mobile/low power. - Always pause the loop when the canvas is off-screen (
IntersectionObserver) and onprefers-reduced-motionrender a static frame. - Soft particles/gooey fluids: GPGPU (ping-pong FBO) (01M4AR8FR…); keep texture size 256-512 squared on mobile.
10. Reduced motion (guidance, not catalogue-observed)
@media (prefers-reduced-motion: reduce){
*,*::before,*::after{ animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; scroll-behavior: auto !important; }
}
Better than a blanket kill: keep state-change feedback (color, check, label) and replace movement with opacity <=150 ms. JS:
const reduce = matchMedia('(prefers-reduced-motion: reduce)')
if (reduce.matches) { lenis.destroy(); ScrollTrigger.getAll().forEach(t=>t.kill()) }
GSAP: gsap.matchMedia().add('(prefers-reduced-motion: no-preference)', () => { /* animations */ }). Stop looping ambient motion (floating elements, glow pulses, marquees), disable autoplaying hero video/3D, and make pinned scroll scenes ordinary stacked sections. Give users a pause control for anything that loops >5 s (WCAG 2.2.2).
11. Performance checklist
- Hover and scroll effects: use
pointermovewithrequestAnimationFramebatching; avoid layout reads in the loop; setwill-change: transformonly during the animation and remove it afterwards. - Heavy effects:
backdrop-filterand largefilter: blur()are the first to drop frames; keep blur radius <= ~20 px on elements < ~1/3 of the viewport, or pre-render a blurred image/video. - Keep one running ambient animation per viewport; pause loops off-screen (
IntersectionObserver). - Preload fonts/media for the first entrance; entrance start offsets <= 300 ms.
- Measure with Performance panel (Rendering -> Frame rendering stats) and Lighthouse INP/CLS; transforms should not trigger layout. Ensure animations do not cause CLS (reserve space).
- Mobile: touch gestures use
touch-action,overscroll-behavior, passive listeners; haptics (navigator.vibrateon Android) are not visible in the catalogue ("haptic" appears in 0 descriptions).