Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59c7859bd4 |
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,210 @@
|
||||
---
|
||||
name: 60fps-animation
|
||||
description: This skill should be used when the user asks to "fix janky CSS animation", "make animation 60fps", "stop layout thrashing", "animate width/height/top/left smoothly", "convert animation to transform", "animate box-shadow performantly", "animate height auto", "FLIP animation", or "why is my scroll/hover animation choppy".
|
||||
version: 0.1.0
|
||||
---
|
||||
|
||||
# Performant Web Animation
|
||||
|
||||
Eliminate the #1 cause of janky web animation: animating properties that force the browser to recalculate layout (reflow) or repaint on every frame. The browser renders in stages — **layout → paint → composite**. Animating `width`, `height`, `top`, `left`, `margin`, `padding`, `box-shadow`, or `filter` re-runs layout and/or paint each frame, blocking the main thread. Animating **`transform`** and **`opacity`** runs entirely on the compositor (often the GPU), skipping layout and paint, which is what makes animation smooth at 60/120fps.
|
||||
|
||||
## When to use
|
||||
|
||||
Use when an animation stutters or drops frames, when a hover/scroll effect feels heavy, when animating size/position/shadow, when a layout change needs to animate smoothly (cards reordering, an element moving between containers), when animating `height: auto`, or when reviewing animation code for performance.
|
||||
|
||||
## Core rule: animate only transform and opacity
|
||||
|
||||
Map every "expensive" animation to a cheap equivalent.
|
||||
|
||||
| Animating (expensive) | Triggers | Replace with (cheap) |
|
||||
|---|---|---|
|
||||
| `width` / `height` | Layout + Paint | `transform: scaleX()/scaleY()` (+ FLIP for true size) |
|
||||
| `top` / `left` / `margin` | Layout + Paint | `transform: translate()` |
|
||||
| `box-shadow` | Paint | Animate `opacity` of a pseudo-element holding the shadow |
|
||||
| `filter: blur()` | Paint (heavy) | Cross-fade two layers via `opacity`, or accept sparingly |
|
||||
| `background-position` | Paint | `transform: translate()` on a child layer |
|
||||
| `color` / `background` | Paint | Often acceptable; or cross-fade layers |
|
||||
|
||||
### Position and size via transform
|
||||
|
||||
```css
|
||||
/* BAD: animates layout every frame */
|
||||
.box { transition: left 300ms, width 300ms; left: 0; width: 100px; }
|
||||
.box:hover { left: 200px; width: 200px; }
|
||||
|
||||
/* GOOD: compositor-only */
|
||||
.box {
|
||||
transition: transform 300ms ease;
|
||||
transform: translateX(0) scaleX(1);
|
||||
transform-origin: left center;
|
||||
}
|
||||
.box:hover { transform: translateX(200px) scaleX(2); }
|
||||
```
|
||||
|
||||
`scaleX` distorts inner content (text stretches). For true resizing without distortion, use **FLIP**.
|
||||
|
||||
## Cheap box-shadow via pseudo-element opacity
|
||||
|
||||
Animating `box-shadow` repaints a large blurred region every frame. Instead paint the shadow once on a `::after`, then animate only its `opacity`.
|
||||
|
||||
```css
|
||||
.card { position: relative; }
|
||||
.card::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: inherit;
|
||||
box-shadow: 0 12px 28px rgba(0,0,0,0.35);
|
||||
opacity: 0;
|
||||
transition: opacity 300ms ease;
|
||||
pointer-events: none;
|
||||
}
|
||||
.card:hover::after { opacity: 1; }
|
||||
```
|
||||
|
||||
The blurred shadow is rasterized once; hovering only changes a compositor opacity — smooth at any frame rate.
|
||||
|
||||
## FLIP: animate layout changes cheaply
|
||||
|
||||
FLIP (First, Last, Invert, Play) animates a *layout* change (reorder, resize, move between containers) using only `transform`. Measure where the element was (First) and will be (Last), apply an inverting transform so it visually appears unmoved, then animate the transform back to identity (Play). The DOM ends in its real final layout; the motion is pure compositor work.
|
||||
|
||||
```js
|
||||
function flip(el, mutate) {
|
||||
const first = el.getBoundingClientRect(); // First
|
||||
mutate(); // change the DOM/layout
|
||||
const last = el.getBoundingClientRect(); // Last
|
||||
|
||||
const dx = first.left - last.left;
|
||||
const dy = first.top - last.top;
|
||||
const sx = first.width / last.width;
|
||||
const sy = first.height / last.height;
|
||||
|
||||
el.animate(
|
||||
[
|
||||
{ transformOrigin: 'top left',
|
||||
transform: `translate(${dx}px, ${dy}px) scale(${sx}, ${sy})` }, // Invert
|
||||
{ transformOrigin: 'top left', transform: 'none' }, // Play
|
||||
],
|
||||
{ duration: 300, easing: 'cubic-bezier(0.2, 0, 0, 1)' }
|
||||
);
|
||||
}
|
||||
|
||||
// usage: animate an element moving to a new grid position
|
||||
flip(card, () => targetContainer.appendChild(card));
|
||||
```
|
||||
|
||||
The Web Animations API `animate()` runs the transform on the compositor. For many elements, batch all `getBoundingClientRect()` reads *before* any mutation (see layout thrashing below).
|
||||
|
||||
## Animating height: auto
|
||||
|
||||
`height: auto` is not interpolatable historically. Modern and fallback approaches:
|
||||
|
||||
```css
|
||||
/* Modern (Chrome 129+/supporting browsers): opt size keywords into animation */
|
||||
.panel {
|
||||
interpolate-size: allow-keywords; /* enables animating to/from auto */
|
||||
height: 0;
|
||||
overflow: clip;
|
||||
transition: height 300ms ease;
|
||||
}
|
||||
.panel.open { height: auto; }
|
||||
/* calc-size() also works: height: calc-size(auto, size); */
|
||||
```
|
||||
|
||||
```css
|
||||
/* Robust fallback today: CSS grid 1fr -> 0fr */
|
||||
.wrapper {
|
||||
display: grid;
|
||||
grid-template-rows: 0fr; /* collapsed */
|
||||
transition: grid-template-rows 300ms ease;
|
||||
}
|
||||
.wrapper.open { grid-template-rows: 1fr; }
|
||||
.wrapper > .content { overflow: hidden; min-height: 0; }
|
||||
```
|
||||
|
||||
The grid trick animates the track size (compositor-friendly enough and broadly supported) and needs no JS height measurement. Use `interpolate-size: allow-keywords` / `calc-size(auto, size)` where the target browsers support it; keep the grid technique as the cross-browser default.
|
||||
|
||||
## Avoid layout thrashing (batch reads, then writes)
|
||||
|
||||
Reading a layout property (`offsetWidth`, `getBoundingClientRect`, `scrollTop`, `getComputedStyle`) after a write forces a *synchronous* reflow. Interleaving reads and writes in a loop ("layout thrashing") can run dozens of forced reflows per frame.
|
||||
|
||||
```js
|
||||
// BAD: read, write, read, write... forces reflow each iteration
|
||||
items.forEach((el) => {
|
||||
const w = el.offsetWidth; // read (forces layout)
|
||||
el.style.width = w * 1.5 + 'px'; // write (invalidates layout)
|
||||
});
|
||||
|
||||
// GOOD: batch all reads, then all writes
|
||||
const widths = items.map((el) => el.offsetWidth); // all reads
|
||||
items.forEach((el, i) => { // all writes
|
||||
el.style.width = widths[i] * 1.5 + 'px';
|
||||
});
|
||||
```
|
||||
|
||||
For frame-synced work, read in a `requestAnimationFrame` callback and apply writes; libraries like fastdom formalize this read/write scheduling.
|
||||
|
||||
## will-change: use sparingly
|
||||
|
||||
`will-change: transform` promotes an element to its own compositor layer ahead of time, avoiding a hitch at animation start. But every promoted layer costs GPU memory, and over-use degrades performance.
|
||||
|
||||
```css
|
||||
.menu { will-change: transform; } /* only on elements about to animate */
|
||||
```
|
||||
|
||||
Rules: apply just before the animation (e.g. on hover/parent state), remove it after (`will-change: auto`) when idle, never blanket-apply to many elements, and never leave it permanently on large/numerous nodes. A single `transform: translateZ(0)` hack does the same promotion but is harder to undo — prefer `will-change`.
|
||||
|
||||
## Deliver & verify (standalone HTML)
|
||||
|
||||
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
|
||||
|
||||
The deliverable is **one self-contained `.html`** that opens directly in a browser — the markup, the CSS/JS animation, and a freeze harness in one file. For this skill, verification is two-pronged: the frame must look right *and* be cheap to produce (compositor-only).
|
||||
|
||||
**Output contract:**
|
||||
- One `.html`, deps via CDN if any, animation driven by CSS transitions/`@keyframes` or the Web Animations API.
|
||||
- A freeze mechanism so a screenshot lands on a deterministic frame:
|
||||
- CSS `@keyframes` → `?t=N` sets `el.style.animationDelay = (-N)+'s'; el.style.animationPlayState = 'paused'`.
|
||||
- WAAPI / JS → keep the animation object and `anim.pause(); anim.currentTime = N*1000`.
|
||||
|
||||
**Verify loop — freeze → screenshot, then profile for jank:**
|
||||
1. Open headless at start / mid / end (`?t=0`, mid, end), screenshot each; confirm the motion is visually correct (no clipped/stretched text from `scaleX`, FLIP lands on the real layout, shadow/height transitions look right).
|
||||
2. **Confirm it's compositor-only** — the whole point of this skill. Either:
|
||||
- DevTools → Performance: record the animation, check there is **no purple "Layout" or green "Paint"** band per frame (only "Composite Layers").
|
||||
- Or headless trace: `npx playwright screenshot` for the visual, plus a CDP/`tracing` capture, and assert no `Layout`/`Paint` events fire during the animation window.
|
||||
3. Watch the FPS/“Frame Rendering Stats” overlay stays at 60 — dropped frames mean an expensive property slipped back in.
|
||||
|
||||
```bash
|
||||
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/anim.html?t=0.3" frame.png
|
||||
```
|
||||
|
||||
**Before you finish:**
|
||||
1. Opens standalone — no console errors.
|
||||
2. Only `transform` / `opacity` animate per frame; DevTools shows no per-frame Layout/Paint.
|
||||
3. Screenshotted at start / mid / end — correct, no `scaleX` text distortion, FLIP lands true.
|
||||
4. Holds 60fps; `will-change` applied just-in-time and removed when idle (no leftover layers).
|
||||
5. `prefers-reduced-motion` honored.
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Goal | Do this |
|
||||
|---|---|
|
||||
| Move element | `transform: translate()` |
|
||||
| Resize without distortion | FLIP with `transform` |
|
||||
| Shadow on hover | Animate `opacity` of shadow pseudo-element |
|
||||
| Expand to content height | grid `0fr→1fr`, or `interpolate-size: allow-keywords` |
|
||||
| Many elements moving | Batch `getBoundingClientRect` reads, then writes |
|
||||
| Smooth animation start | `will-change` just-in-time, remove when idle |
|
||||
| Verify it's compositor-only | DevTools Performance: no purple "Layout"/green "Paint" per frame |
|
||||
|
||||
## Gotchas
|
||||
|
||||
- `scaleX/scaleY` stretches text and children; use FLIP when content must stay crisp.
|
||||
- `transform` percentages are relative to the element's own box, not the parent — different from `left: %`.
|
||||
- Overusing `will-change` or `translateZ(0)` creates too many layers and *hurts* performance; promote only what animates.
|
||||
- `filter` and `backdrop-filter` are compositor-related but still expensive; animate their presence via opacity cross-fades rather than animating the blur radius.
|
||||
- The grid `1fr→0fr` content must have `overflow: hidden` and `min-height: 0` or it won't collapse.
|
||||
- Always gate non-essential motion behind `@media (prefers-reduced-motion: reduce)`.
|
||||
|
||||
## Reference files
|
||||
|
||||
- `references/patterns-and-profiling.md` — full runnable examples (accordion, reorder list, parallax), DevTools profiling walkthrough to confirm compositor-only frames, reduced-motion patterns, and a property-cost cheat sheet.
|
||||
@@ -0,0 +1,132 @@
|
||||
# Patterns, profiling, and cost cheat sheet
|
||||
|
||||
## Property cost cheat sheet
|
||||
|
||||
| Property | Pipeline stage triggered | Verdict |
|
||||
|---|---|---|
|
||||
| `transform` | Composite only | Cheap — animate freely |
|
||||
| `opacity` | Composite only | Cheap — animate freely |
|
||||
| `filter` | Paint (+composite) | Expensive — avoid animating radius |
|
||||
| `box-shadow` | Paint (large area) | Expensive — use pseudo + opacity |
|
||||
| `width`, `height` | Layout + Paint | Avoid — use scale/FLIP |
|
||||
| `top`, `left`, `right`, `bottom` | Layout + Paint | Avoid — use translate |
|
||||
| `margin`, `padding` | Layout + Paint | Avoid |
|
||||
| `border-width` | Layout + Paint | Avoid |
|
||||
| `color`, `background-color` | Paint | Acceptable in moderation |
|
||||
| `background-position` | Paint | Prefer translate on child |
|
||||
| `clip-path` | Paint | Moderate; cheaper than filter |
|
||||
|
||||
## Accordion with grid height (no JS measurement)
|
||||
|
||||
```html
|
||||
<button class="acc-trigger" aria-expanded="false">Details</button>
|
||||
<div class="acc-wrap"><div class="acc-content">…content…</div></div>
|
||||
```
|
||||
|
||||
```css
|
||||
.acc-wrap {
|
||||
display: grid;
|
||||
grid-template-rows: 0fr;
|
||||
transition: grid-template-rows 280ms cubic-bezier(0.2,0,0,1);
|
||||
}
|
||||
.acc-wrap.open { grid-template-rows: 1fr; }
|
||||
.acc-content { overflow: hidden; min-height: 0; }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.acc-wrap { transition: none; }
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
trigger.addEventListener('click', () => {
|
||||
const open = wrap.classList.toggle('open');
|
||||
trigger.setAttribute('aria-expanded', String(open));
|
||||
});
|
||||
```
|
||||
|
||||
## FLIP reorder list (batched reads)
|
||||
|
||||
```js
|
||||
function flipReorder(container, mutate) {
|
||||
const items = [...container.children];
|
||||
const firsts = new Map(items.map((el) => [el, el.getBoundingClientRect()])); // all reads
|
||||
|
||||
mutate(); // e.g. sort/reinsert children
|
||||
|
||||
items.forEach((el) => {
|
||||
const first = firsts.get(el);
|
||||
const last = el.getBoundingClientRect();
|
||||
const dx = first.left - last.left;
|
||||
const dy = first.top - last.top;
|
||||
if (dx || dy) {
|
||||
el.animate(
|
||||
[{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }],
|
||||
{ duration: 300, easing: 'cubic-bezier(0.2,0,0,1)' }
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Reading every rect *before* mutating, and using `animate()` (compositor), keeps a 50-item reorder smooth.
|
||||
|
||||
## Just-in-time will-change
|
||||
|
||||
```js
|
||||
el.addEventListener('pointerenter', () => { el.style.willChange = 'transform'; });
|
||||
el.addEventListener('transitionend', () => { el.style.willChange = 'auto'; });
|
||||
```
|
||||
|
||||
Promote on intent, demote when the animation ends, so layers don't accumulate.
|
||||
|
||||
## Reduced-motion gate
|
||||
|
||||
```css
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after {
|
||||
animation-duration: 0.001ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.001ms !important;
|
||||
scroll-behavior: auto !important;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
For JS: `const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;` and skip/shorten animations when true.
|
||||
|
||||
## Profiling: prove it's compositor-only
|
||||
|
||||
1. Open DevTools > **Performance**. Record while the animation runs.
|
||||
2. Inspect the flame chart frames during the animation:
|
||||
- **Purple "Layout"** or **green "Paint"** bars on every frame → still hitting layout/paint; the animation is not compositor-only. Find the offending property.
|
||||
- Only **"Composite Layers"** / GPU work per frame → success.
|
||||
3. Use **Rendering** tab tools:
|
||||
- **Paint flashing** — green flashes show repainted regions; a good transform/opacity animation flashes nothing.
|
||||
- **Layer borders** — confirms which elements are on their own compositor layer (watch for too many from over-using `will-change`).
|
||||
- **Frame Rendering Stats / FPS meter** — confirm a stable 60/120fps.
|
||||
4. The **Layers** panel shows layer count and memory; excessive layers indicate `will-change` overuse.
|
||||
|
||||
## Parallax without scroll-jank
|
||||
|
||||
Drive parallax with `transform: translate3d()` updated inside a single `requestAnimationFrame` loop reading `scrollY` once per frame — never read layout per element per frame.
|
||||
|
||||
```js
|
||||
let ticking = false;
|
||||
addEventListener('scroll', () => {
|
||||
if (!ticking) {
|
||||
requestAnimationFrame(() => {
|
||||
const y = window.scrollY; // single read
|
||||
layers.forEach((l, i) => { // writes only
|
||||
l.style.transform = `translate3d(0, ${y * (0.1 * (i + 1))}px, 0)`;
|
||||
});
|
||||
ticking = false;
|
||||
});
|
||||
ticking = true;
|
||||
}
|
||||
}, { passive: true });
|
||||
```
|
||||
|
||||
`{ passive: true }` lets the browser scroll without waiting on the handler.
|
||||
|
||||
---
|
||||
Stay on transform and opacity, profile the jank away, and motion holds 60fps. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=60fps-animation)** — the AI motion agent for editable, on-brand motion graphics.
|
||||
Whitespace-only changes.
@@ -0,0 +1,231 @@
|
||||
---
|
||||
name: accessible-animation
|
||||
description: This skill should be used when the user asks to "respect prefers-reduced-motion", "honor reduced motion", "make my animations accessible", "fix vestibular / motion-sickness issues", "add a useReducedMotion hook", "gate GSAP / Framer Motion / Lenis for reduced motion", or "meet WCAG 2.3.3 / C39". Provides tiered (not all-or-nothing) reduced-motion patterns in CSS and JS.
|
||||
version: 0.1.0
|
||||
---
|
||||
|
||||
# Accessible Animation (Reduced Motion, Tiered)
|
||||
|
||||
Honor `prefers-reduced-motion: reduce` as a *graceful degradation*, not a kill switch. The OS-level setting (macOS: Settings > Accessibility > Display > Reduce motion; Windows: Settings > Accessibility > Visual effects > Animation effects; iOS/Android equivalents) signals that *vestibular-triggering* motion causes nausea, dizziness, or migraines. The correct response is to remove the dangerous motion while keeping orientation cues.
|
||||
|
||||
## When to use
|
||||
|
||||
Use when adding or auditing animation in a web UI, when a user reports motion sickness or WCAG findings, or when integrating animation libraries (GSAP, Framer Motion, Lenis smooth scroll, Anime.js, CSS keyframes) into an accessible product.
|
||||
|
||||
## The core principle: tier motion, do not nuke it
|
||||
|
||||
Removing *all* animation is a common over-correction. An instant state change with no transition can be more disorienting (elements teleport) and removes useful affordances (focus rings, loading spinners that communicate progress). Sort every animation into three tiers:
|
||||
|
||||
- **Tier 1 — Remove entirely (vestibular triggers).** Parallax; large-area slides/translates across the viewport; scale/zoom of large elements; 3D rotation and spin; continuous auto-playing carousels and marquees; smooth-scroll hijacking (Lenis/Locomotive); scroll-jacked pinned scenes; motion-path animation; anything that moves a large portion of the screen or implies depth/self-motion.
|
||||
- **Tier 2 — Soften / shorten.** Replace movement with a short opacity fade (≤200ms). Reduce distance and duration. Keep the *fact* of a transition (so elements don't teleport) but strip the displacement. Replace a 600ms slide-in-from-left with a 150ms cross-fade.
|
||||
- **Tier 3 — Always keep.** Opacity fades, color/background transitions, focus-ring transitions, loading indicators, and motion that is *essential* to meaning (WCAG allows essential animation). These rarely trigger vestibular responses because they imply no self-motion.
|
||||
|
||||
## CSS layer: media-query gating
|
||||
|
||||
Write motion as the default, then override under the reduce query. Prefer a global safety net plus targeted overrides.
|
||||
|
||||
```css
|
||||
/* Global safety net: neutralize runaway motion but DO NOT set 0s blindly,
|
||||
which can break JS that waits for transitionend/animationend. Use 0.01ms. */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important; /* stop infinite spins/marquees */
|
||||
transition-duration: 0.01ms !important;
|
||||
scroll-behavior: auto !important; /* kill smooth scroll */
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The global net is a backstop. Layer *intentional, tiered* overrides on top so Tier 3 motion survives:
|
||||
|
||||
```css
|
||||
.card {
|
||||
transition: transform 400ms ease, opacity 400ms ease, background-color 200ms ease;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.card {
|
||||
/* Tier 2: drop the transform (movement), keep opacity + color (Tier 3) */
|
||||
transition: opacity 150ms ease, background-color 150ms ease;
|
||||
}
|
||||
.parallax-layer { transform: none !important; } /* Tier 1: remove */
|
||||
.hero-zoom { animation: none !important; } /* Tier 1: remove */
|
||||
}
|
||||
```
|
||||
|
||||
Use the *positive* query `(prefers-reduced-motion: no-preference)` to opt motion IN, which is the safest pattern for elaborate effects:
|
||||
|
||||
```css
|
||||
.hero { opacity: 1; } /* visible, static by default */
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.hero { animation: zoom-in 1.2s ease both; } /* only animate when allowed */
|
||||
}
|
||||
```
|
||||
|
||||
## JS layer: matchMedia gating
|
||||
|
||||
CSS cannot gate JS-driven animation (GSAP timelines, Framer's `animate`, canvas/WebGL, Lenis). Read the same signal via `matchMedia` and react to live changes (users toggle the OS setting without reloading).
|
||||
|
||||
```js
|
||||
const REDUCE_QUERY = '(prefers-reduced-motion: reduce)';
|
||||
|
||||
export function prefersReducedMotion() {
|
||||
return typeof window !== 'undefined'
|
||||
&& window.matchMedia
|
||||
&& window.matchMedia(REDUCE_QUERY).matches;
|
||||
}
|
||||
|
||||
// Live updates: listen so toggling the OS setting takes effect immediately.
|
||||
export function onReducedMotionChange(cb) {
|
||||
const mq = window.matchMedia(REDUCE_QUERY);
|
||||
const handler = (e) => cb(e.matches);
|
||||
mq.addEventListener('change', handler); // modern API
|
||||
return () => mq.removeEventListener('change', handler);
|
||||
}
|
||||
```
|
||||
|
||||
### Library gating, applied as one reusable layer
|
||||
|
||||
```js
|
||||
// GSAP — use matchMedia(): GSAP reverts conditional setups on change.
|
||||
import gsap from 'gsap';
|
||||
const mm = gsap.matchMedia();
|
||||
mm.add({
|
||||
motionOK: '(prefers-reduced-motion: no-preference)',
|
||||
motionReduce: '(prefers-reduced-motion: reduce)',
|
||||
}, (ctx) => {
|
||||
const { motionOK } = ctx.conditions;
|
||||
if (motionOK) {
|
||||
gsap.from('.hero', { y: 80, opacity: 0, duration: 1 }); // Tier 1 move
|
||||
} else {
|
||||
gsap.from('.hero', { opacity: 0, duration: 0.15 }); // Tier 2 fade
|
||||
}
|
||||
});
|
||||
|
||||
// Lenis smooth scroll — do not instantiate at all when reduced.
|
||||
import Lenis from 'lenis';
|
||||
let lenis = null;
|
||||
if (!prefersReducedMotion()) {
|
||||
lenis = new Lenis();
|
||||
const raf = (t) => { lenis.raf(t); requestAnimationFrame(raf); };
|
||||
requestAnimationFrame(raf);
|
||||
}
|
||||
```
|
||||
|
||||
## React: a `useReducedMotion` hook
|
||||
|
||||
```jsx
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
export function useReducedMotion() {
|
||||
const query = '(prefers-reduced-motion: reduce)';
|
||||
const get = () =>
|
||||
typeof window !== 'undefined' && window.matchMedia
|
||||
? window.matchMedia(query).matches
|
||||
: false;
|
||||
const [reduced, setReduced] = useState(get);
|
||||
|
||||
useEffect(() => {
|
||||
const mq = window.matchMedia(query);
|
||||
const onChange = () => setReduced(mq.matches);
|
||||
onChange(); // sync after hydration
|
||||
mq.addEventListener('change', onChange);
|
||||
return () => mq.removeEventListener('change', onChange);
|
||||
}, []);
|
||||
|
||||
return reduced;
|
||||
}
|
||||
```
|
||||
|
||||
```jsx
|
||||
// Framer Motion has its own useReducedMotion(); the hook above also works.
|
||||
import { motion } from 'framer-motion';
|
||||
function Card() {
|
||||
const reduced = useReducedMotion();
|
||||
return (
|
||||
<motion.div
|
||||
initial={reduced ? { opacity: 0 } : { opacity: 0, y: 40 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: reduced ? 0.15 : 0.5 }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Initialize SSR-rendered state to `false` (motion) and re-sync in `useEffect` to avoid a hydration mismatch; the OS value is only known client-side.
|
||||
|
||||
## WCAG mapping
|
||||
|
||||
- **2.3.3 Animation from Interactions (AAA).** Motion triggered by interaction (scroll, hover) must be disable-able unless essential. Honoring `prefers-reduced-motion` is the standard technique.
|
||||
- **C39 (CSS technique).** Use the `prefers-reduced-motion` query to prevent motion. This is the named sufficient technique.
|
||||
- **2.2.2 Pause, Stop, Hide (A).** Any auto-playing motion lasting >5s must offer pause/stop. Auto-carousels and marquees fail this regardless of the media query — give a control too.
|
||||
|
||||
## Deliver & verify (standalone HTML)
|
||||
|
||||
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
|
||||
|
||||
For a self-contained demo the deliverable is **one HTML file that opens directly in a browser** — markup, CSS, and any JS (GSAP/`matchMedia` from CDN) inline, no build step. For *this* skill the verification is the point: you must screenshot **both** the normal and the reduced-motion path and confirm the tiering is correct.
|
||||
|
||||
**Output contract:**
|
||||
- One `.html` file with the full motion AND its tiered reduced-motion overrides (CSS query + `matchMedia`/`gsap.matchMedia()` for JS-driven motion).
|
||||
- A seek harness to freeze a frame, plus a way to force the reduced-motion code path for screenshots.
|
||||
|
||||
**Seek harness — freeze a frame, force the preference.** `?t=N` freezes the timeline; `?reduce=1` forces the reduced path even when the OS setting is off (CSS can't be toggled from JS, so query the same flag you gate JS on, and screenshot with the OS/browser preference emulated for the CSS layer):
|
||||
|
||||
```html
|
||||
<script>
|
||||
const q = new URLSearchParams(location.search);
|
||||
const reduce = q.get("reduce") === "1"
|
||||
|| window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
// build motion conditionally on `reduce` (Tier-1 removed, Tier-2 softened, Tier-3 kept)
|
||||
const t = q.get("t");
|
||||
if (t !== null) { tl.pause(); tl.seek(parseFloat(t)); } // GSAP; CSS: el.style.animationDelay=(-t)+"s"; playState="paused"
|
||||
window.__ready = true;
|
||||
</script>
|
||||
```
|
||||
|
||||
**Verify loop — screenshot BOTH states:** capture the normal path AND the reduced path, mid-animation each, and confirm Tier-1 motion is gone, Tier-2 is a short fade, Tier-3 survives. Emulate the preference for the CSS layer (Playwright `--reduced-motion=reduce`; the agent's browser tool can emulate it too):
|
||||
|
||||
```bash
|
||||
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/demo.html?t=0.6" normal.png
|
||||
npx playwright screenshot --reduced-motion=reduce --wait-for-timeout=500 "file://$PWD/demo.html?t=0.6&reduce=1" reduced.png
|
||||
```
|
||||
|
||||
**Before you finish:**
|
||||
1. Opens standalone — no console errors, CDN (if any) loads.
|
||||
2. The freeze + `?reduce=1` (and `--reduced-motion=reduce`) reliably exercises both code paths.
|
||||
3. Screenshotted in BOTH states, mid-animation — normal looks intentional, reduced strips Tier-1/softens Tier-2.
|
||||
4. `prefers-reduced-motion` honored as *tiering*, not a kill switch — no teleporting, Tier-3 fades/focus rings/spinners kept; any >5s auto-motion still has a pause control (2.2.2).
|
||||
5. Easing is intentional in both paths — no accidental `linear`, durations sane (reduced fades ≤200ms, `0.01ms` not `0s`).
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Motion type | Tier | Reduced behavior |
|
||||
|---|---|---|
|
||||
| Parallax / depth | 1 | Remove (`transform: none`) |
|
||||
| Large slide / translate | 1 | Remove or replace with fade |
|
||||
| Scale / zoom (large) | 1 | Remove |
|
||||
| Spin / 3D rotate | 1 | Remove (`animation: none`) |
|
||||
| Auto carousel / marquee | 1 | Stop + provide pause control (2.2.2) |
|
||||
| Smooth-scroll (Lenis) | 1 | Don't instantiate |
|
||||
| Small slide / pop-in | 2 | Cross-fade ≤200ms |
|
||||
| Opacity fade | 3 | Keep (shorten if long) |
|
||||
| Color / focus-ring transition | 3 | Keep |
|
||||
| Loading spinner | 3 | Keep (essential feedback) |
|
||||
|
||||
## Gotchas
|
||||
|
||||
- `animation-duration: 0s` can break code waiting on `animationend`/`transitionend`; use `0.01ms` so the event still fires.
|
||||
- The global `*` reset alone over-removes Tier 3 motion; always layer intentional overrides.
|
||||
- Forgetting `animation-iteration-count: 1` leaves infinite spins running at near-zero duration (CPU churn, still animating).
|
||||
- No media query covers JS/canvas/WebGL — gate those with `matchMedia` or the loop never stops.
|
||||
- Toggling the OS setting fires no page reload; without a `change` listener the page keeps its stale state.
|
||||
- SSR: reading `matchMedia` during render throws or mismatches; default to motion and sync in an effect.
|
||||
- Auto-playing motion needs a visible pause control even when reduced-motion is off (2.2.2 is Level A).
|
||||
|
||||
## Reference files
|
||||
|
||||
- `references/patterns.md` — Full GSAP `matchMedia` teardown, Framer Motion `MotionConfig`, Lenis start/stop on live toggle, a reusable `animateWithMotionPreference` wrapper, marquee with pause control, and a tier-classification audit checklist.
|
||||
@@ -0,0 +1,196 @@
|
||||
# Reduced Motion — Detailed Patterns
|
||||
|
||||
## Reusable wrapper: animate with motion preference
|
||||
|
||||
A single helper that picks a "full" or "reduced" variant and stays live-reactive.
|
||||
|
||||
```js
|
||||
const REDUCE = '(prefers-reduced-motion: reduce)';
|
||||
|
||||
export function createMotionController() {
|
||||
const mq = window.matchMedia(REDUCE);
|
||||
const listeners = new Set();
|
||||
mq.addEventListener('change', () => listeners.forEach((fn) => fn(mq.matches)));
|
||||
|
||||
return {
|
||||
get reduced() { return mq.matches; },
|
||||
subscribe(fn) { listeners.add(fn); fn(mq.matches); return () => listeners.delete(fn); },
|
||||
// Pick a variant object: { full, reduced }
|
||||
pick(variants) { return mq.matches ? variants.reduced : variants.full; },
|
||||
};
|
||||
}
|
||||
|
||||
// Usage
|
||||
const motion = createMotionController();
|
||||
const opts = motion.pick({
|
||||
full: { translateY: ['40px', '0'], opacity: [0, 1], duration: 500 },
|
||||
reduced: { opacity: [0, 1], duration: 150 },
|
||||
});
|
||||
```
|
||||
|
||||
## GSAP: full matchMedia with teardown
|
||||
|
||||
`gsap.matchMedia()` automatically reverts (kills tweens, restores inline styles) when a condition stops matching, so toggling the OS setting cleans up correctly.
|
||||
|
||||
```js
|
||||
import gsap from 'gsap';
|
||||
import { ScrollTrigger } from 'gsap/ScrollTrigger';
|
||||
gsap.registerPlugin(ScrollTrigger);
|
||||
|
||||
const mm = gsap.matchMedia();
|
||||
|
||||
mm.add({
|
||||
motionOK: '(prefers-reduced-motion: no-preference)',
|
||||
motionReduce: '(prefers-reduced-motion: reduce)',
|
||||
}, (ctx) => {
|
||||
const { motionOK } = ctx.conditions;
|
||||
|
||||
if (motionOK) {
|
||||
// Tier 1 parallax — only when allowed
|
||||
gsap.to('.parallax-layer', {
|
||||
yPercent: -30,
|
||||
ease: 'none',
|
||||
scrollTrigger: { trigger: '.section', scrub: true },
|
||||
});
|
||||
gsap.from('.card', {
|
||||
y: 60, opacity: 0, stagger: 0.1,
|
||||
scrollTrigger: { trigger: '.grid', start: 'top 80%' },
|
||||
});
|
||||
} else {
|
||||
// Reduced: no parallax at all; cards cross-fade in place (Tier 2)
|
||||
gsap.from('.card', {
|
||||
opacity: 0, duration: 0.15, stagger: 0.03,
|
||||
scrollTrigger: { trigger: '.grid', start: 'top 80%' },
|
||||
});
|
||||
}
|
||||
|
||||
return () => { /* optional extra cleanup; mm reverts tweens automatically */ };
|
||||
});
|
||||
|
||||
// Tear everything down (e.g. SPA route change)
|
||||
// mm.revert();
|
||||
```
|
||||
|
||||
## Framer Motion: MotionConfig for app-wide reduction
|
||||
|
||||
`MotionConfig reducedMotion="user"` makes every child `motion` component automatically drop transform/layout animations while keeping opacity. Set it once at the root.
|
||||
|
||||
```jsx
|
||||
import { MotionConfig, motion } from 'framer-motion';
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<MotionConfig reducedMotion="user">
|
||||
{/* All descendant motion components honor the OS setting */}
|
||||
<motion.section
|
||||
initial={{ opacity: 0, y: 80 }} // y is auto-dropped when reduced
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.6 }}
|
||||
/>
|
||||
</MotionConfig>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
For per-component control, Framer's own hook:
|
||||
|
||||
```jsx
|
||||
import { useReducedMotion } from 'framer-motion';
|
||||
|
||||
function Hero() {
|
||||
const reduced = useReducedMotion();
|
||||
const variants = reduced
|
||||
? { hidden: { opacity: 0 }, show: { opacity: 1, transition: { duration: 0.15 } } }
|
||||
: { hidden: { opacity: 0, scale: 0.9 }, show: { opacity: 1, scale: 1, transition: { duration: 0.8 } } };
|
||||
return <motion.div variants={variants} initial="hidden" animate="show" />;
|
||||
}
|
||||
```
|
||||
|
||||
## Lenis: start/stop on live toggle
|
||||
|
||||
Lenis hijacks scroll (Tier 1). Destroy it when reduced motion turns on, recreate when it turns off.
|
||||
|
||||
```js
|
||||
import Lenis from 'lenis';
|
||||
|
||||
let lenis = null;
|
||||
let rafId = null;
|
||||
|
||||
function startLenis() {
|
||||
if (lenis) return;
|
||||
lenis = new Lenis({ smoothWheel: true });
|
||||
const loop = (t) => { lenis.raf(t); rafId = requestAnimationFrame(loop); };
|
||||
rafId = requestAnimationFrame(loop);
|
||||
}
|
||||
function stopLenis() {
|
||||
if (!lenis) return;
|
||||
cancelAnimationFrame(rafId);
|
||||
lenis.destroy();
|
||||
lenis = null;
|
||||
// Restore native scroll so the page is still usable
|
||||
document.documentElement.style.removeProperty('scroll-behavior');
|
||||
}
|
||||
|
||||
const mq = window.matchMedia('(prefers-reduced-motion: reduce)');
|
||||
function sync() { mq.matches ? stopLenis() : startLenis(); }
|
||||
mq.addEventListener('change', sync);
|
||||
sync();
|
||||
```
|
||||
|
||||
## Auto-carousel / marquee with a pause control (WCAG 2.2.2)
|
||||
|
||||
Auto-playing motion longer than 5s needs a pause/stop control regardless of the media query. Reduced-motion users get it stopped by default; everyone gets the control.
|
||||
|
||||
```html
|
||||
<div class="marquee" data-playing="true">
|
||||
<button class="marquee__toggle" aria-pressed="false">Pause</button>
|
||||
<ul class="marquee__track"><!-- items --></ul>
|
||||
</div>
|
||||
```
|
||||
|
||||
```css
|
||||
.marquee__track { animation: scroll-left 20s linear infinite; }
|
||||
.marquee[data-playing="false"] .marquee__track { animation-play-state: paused; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.marquee__track { animation-play-state: paused; } /* paused by default */
|
||||
}
|
||||
@keyframes scroll-left { to { transform: translateX(-50%); } }
|
||||
```
|
||||
|
||||
```js
|
||||
const root = document.querySelector('.marquee');
|
||||
const btn = root.querySelector('.marquee__toggle');
|
||||
// Respect the OS setting for the initial state
|
||||
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
|
||||
root.dataset.playing = 'false';
|
||||
btn.textContent = 'Play';
|
||||
btn.setAttribute('aria-pressed', 'true');
|
||||
}
|
||||
btn.addEventListener('click', () => {
|
||||
const playing = root.dataset.playing === 'true';
|
||||
root.dataset.playing = String(!playing);
|
||||
btn.textContent = playing ? 'Play' : 'Pause';
|
||||
btn.setAttribute('aria-pressed', String(playing));
|
||||
});
|
||||
```
|
||||
|
||||
## Tier classification audit checklist
|
||||
|
||||
For each animation in the codebase, ask in order:
|
||||
|
||||
1. Is it essential to meaning (e.g. a progress bar, a diagram step)? -> Tier 3, keep.
|
||||
2. Does a large area move, scale, spin, or imply depth/self-motion (parallax, zoom hero, slide-over)? -> Tier 1, remove under reduce.
|
||||
3. Is it a small entrance with displacement (pop-in, slide-up)? -> Tier 2, replace displacement with a ≤200ms opacity fade.
|
||||
4. Is it only opacity/color/focus? -> Tier 3, keep (shorten if >300ms).
|
||||
5. Does it auto-play >5s (carousel, marquee, looping video bg)? -> Add a pause control (2.2.2) on top of any tier handling.
|
||||
|
||||
## Testing
|
||||
|
||||
- macOS: System Settings > Accessibility > Display > Reduce motion.
|
||||
- Windows 11: Settings > Accessibility > Visual effects > Animation effects (off).
|
||||
- Chrome DevTools: Rendering panel > "Emulate CSS media feature prefers-reduced-motion".
|
||||
- Verify the `change` listener: toggle the OS setting with the page open and confirm motion stops without reload.
|
||||
- Confirm `transitionend`/`animationend`-dependent flows still complete (the `0.01ms` rule).
|
||||
|
||||
---
|
||||
Honor prefers-reduced-motion at every tier and motion stays inclusive by default. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=accessible-animation)** — the AI motion agent for editable, on-brand motion graphics.
|
||||
Whitespace-only changes.
@@ -0,0 +1,179 @@
|
||||
---
|
||||
name: ascii-animation
|
||||
description: This skill should be used when the user asks to "make an ASCII animation", "build a terminal/CLI intro or loader", "convert an image or video to ASCII art", "add an ASCII shader/post-effect to a canvas or Three.js scene", "create retro/hacker text-character motion", or "animate text characters with a brightness ramp". Covers generative ASCII fields, image/video/3D-to-ASCII, and animated character art for both web and terminal.
|
||||
version: 0.1.0
|
||||
---
|
||||
|
||||
# ASCII Animation
|
||||
|
||||
Render motion entirely with text characters. ASCII output is extremely lightweight, distinctive, and works in browsers (`<pre>`/canvas), terminals (ANSI), and over any 3D scene (Three.js `AsciiEffect`).
|
||||
|
||||
## When to use
|
||||
|
||||
- Build terminal/CLI intros, loaders, banners, or a retro/hacker aesthetic.
|
||||
- Convert an image, video frame, or 3D scene into animated ASCII.
|
||||
- Add an ASCII post-effect over an existing canvas/WebGL render.
|
||||
- Create generative text fields (plasma, sine waves, noise, tunnels).
|
||||
|
||||
## Core concept: the brightness ramp
|
||||
|
||||
Map luminance (0..1) to a character whose ink density matches. Order characters dark-to-light. Pick the index with `Math.round(lum * (ramp.length - 1))`.
|
||||
|
||||
Common ramps (dark to light):
|
||||
- Short (10): ` .:-=+*#%@`
|
||||
- Medium (16): ` .'\`^",:;Il!i><~+_-?][}{1)(|/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$` truncated — see table below.
|
||||
- Standard 70-level (Paul Bourke), best for photos:
|
||||
`` $@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'. `` (reverse for dark-on-light).
|
||||
|
||||
Compute relative luminance from sRGB (perceptual):
|
||||
```js
|
||||
const lum = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255; // 0..1
|
||||
```
|
||||
|
||||
Invert when drawing dark text on a light background: `lum = 1 - lum`.
|
||||
|
||||
## Character cell aspect correction (the #1 gotcha)
|
||||
|
||||
Monospace character cells are taller than wide — roughly **0.5 width:height**. Sampling a square pixel grid produces a vertically stretched image. Correct by sampling **fewer rows than columns**: for a target of `cols` characters wide, use `rows = Math.round(cols * (imgH / imgW) * fontAspect)` where `fontAspect ≈ 0.5`. Equivalently, when drawing to an offscreen canvas, set its height to `cols * aspect * 0.5`.
|
||||
|
||||
## Web rendering: `<pre>` vs canvas
|
||||
|
||||
- **`<pre>` + textContent**: simplest. One string with `\n` per row. Fine up to ~120×60 chars at 30fps. Set `white-space: pre; font-family: monospace; line-height: 1;`.
|
||||
- **Canvas `fillText`**: needed for per-character color, larger grids, or 60fps. Draw each char at `x * cellW, y * cellH`. Faster than thousands of DOM nodes.
|
||||
|
||||
Generative `<pre>` field (plasma):
|
||||
```js
|
||||
const pre = document.querySelector('pre');
|
||||
const COLS = 100, ROWS = 50, ramp = ' .:-=+*#%@';
|
||||
function frame(t) {
|
||||
let out = '';
|
||||
for (let y = 0; y < ROWS; y++) {
|
||||
for (let x = 0; x < COLS; x++) {
|
||||
const v = Math.sin(x * 0.2 + t * 0.001)
|
||||
+ Math.sin(y * 0.3 + t * 0.0013)
|
||||
+ Math.sin((x + y) * 0.15 + t * 0.0007);
|
||||
const lum = (v + 3) / 6; // normalize -3..3 to 0..1
|
||||
out += ramp[Math.round(lum * (ramp.length - 1))];
|
||||
}
|
||||
out += '\n';
|
||||
}
|
||||
pre.textContent = out;
|
||||
requestAnimationFrame(frame);
|
||||
}
|
||||
requestAnimationFrame(frame);
|
||||
```
|
||||
|
||||
## Image / video to ASCII
|
||||
|
||||
Draw the source to a small offscreen canvas at `cols × rows`, read pixels with `getImageContext().getImageData`, then map each pixel to a character. For video, repeat per frame from a `<video>` element.
|
||||
|
||||
```js
|
||||
function videoToAscii(video, cols = 120) {
|
||||
const aspect = video.videoHeight / video.videoWidth;
|
||||
const rows = Math.round(cols * aspect * 0.5); // cell aspect correction
|
||||
const cv = document.createElement('canvas');
|
||||
cv.width = cols; cv.height = rows;
|
||||
const ctx = cv.getContext('2d', { willReadFrequently: true });
|
||||
const ramp = ' .:-=+*#%@', pre = document.querySelector('pre');
|
||||
(function tick() {
|
||||
ctx.drawImage(video, 0, 0, cols, rows);
|
||||
const { data } = ctx.getImageData(0, 0, cols, rows);
|
||||
let out = '';
|
||||
for (let i = 0; i < data.length; i += 4) {
|
||||
const lum = (0.2126*data[i] + 0.7152*data[i+1] + 0.0722*data[i+2]) / 255;
|
||||
out += ramp[Math.round(lum * (ramp.length - 1))];
|
||||
if (((i / 4) + 1) % cols === 0) out += '\n';
|
||||
}
|
||||
pre.textContent = out;
|
||||
requestAnimationFrame(tick);
|
||||
})();
|
||||
}
|
||||
```
|
||||
|
||||
For Node image→ASCII, see `scripts/img-to-ascii.mjs`.
|
||||
|
||||
## 3D-to-ASCII with Three.js
|
||||
|
||||
`AsciiEffect` wraps a renderer and renders any scene as ASCII into a DOM element. Render through the effect, not the renderer.
|
||||
|
||||
```js
|
||||
import { AsciiEffect } from 'three/addons/effects/AsciiEffect.js';
|
||||
const effect = new AsciiEffect(renderer, ' .:-=+*#%@', { invert: true });
|
||||
effect.setSize(innerWidth, innerHeight);
|
||||
effect.domElement.style.color = '#0f0';
|
||||
effect.domElement.style.backgroundColor = 'black';
|
||||
document.body.appendChild(effect.domElement);
|
||||
// in loop: effect.render(scene, camera); // NOT renderer.render
|
||||
```
|
||||
|
||||
## Terminal / CLI animation
|
||||
|
||||
Loop with ANSI escape codes: hide the cursor, move to home, print the frame, throttle to 12–24 fps. Show the cursor again on exit.
|
||||
|
||||
```js
|
||||
const ESC = '\x1b[';
|
||||
process.stdout.write(ESC + '?25l'); // hide cursor
|
||||
function frame(t) {
|
||||
process.stdout.write(ESC + 'H'); // cursor to top-left
|
||||
// build and write rows...
|
||||
}
|
||||
const id = setInterval(() => frame(Date.now()), 1000 / 20);
|
||||
process.on('SIGINT', () => {
|
||||
clearInterval(id);
|
||||
process.stdout.write(ESC + '?25h' + ESC + '2J'); // show cursor, clear
|
||||
process.exit();
|
||||
});
|
||||
```
|
||||
Use `ESC + '2J'` to clear the whole screen, `ESC + 'H'` for home (cheaper per frame than clearing). Color with `\x1b[38;2;R;G;Bm` (truecolor) and reset with `\x1b[0m`.
|
||||
|
||||
## Deliver & verify (standalone HTML)
|
||||
|
||||
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
|
||||
|
||||
For a self-contained web ASCII piece (generative field, image/video→ASCII, `AsciiEffect` scene) the deliverable is **one HTML file that opens directly in a browser** — the `<pre>`/canvas, the ramp, and the rAF loop inline (Three.js from CDN if used). No build step. One file is the right tier; don't reach for a bundler. (Terminal/CLI pieces verify differently — capture stdout or a screenshot of the terminal.)
|
||||
|
||||
**Output contract:**
|
||||
- One `.html` file: the render target, the brightness ramp, and the `requestAnimationFrame` loop in one inline `<script>`.
|
||||
- Drive frames from an **injectable time** (not `Date.now()`/`performance.now()` directly) and seed any randomness, so a frame is reproducible.
|
||||
|
||||
**Seek harness — freeze the rAF loop on a deterministic frame.** `?t=N` renders exactly one frame at simulated time `N` instead of looping, so a screenshot is reproducible. Feed `N` where the loop reads time, and fix the seed:
|
||||
|
||||
```html
|
||||
<script>
|
||||
const t = new URLSearchParams(location.search).get("t");
|
||||
// your frame(time){…} reads `time`, not Date.now(); RNG uses a fixed seed
|
||||
if (t !== null) { frame(parseFloat(t)); } // render ONE frame, no rAF
|
||||
else { (function loop(now){ frame(now); requestAnimationFrame(loop); })(0); }
|
||||
window.__ready = true;
|
||||
</script>
|
||||
```
|
||||
|
||||
**Verify loop — render → freeze → screenshot → check:** render at a few simulated times (`?t=0`, `?t=1000`, `?t=2000`), screenshot each, and check **fidelity** (ramp reads dark→light correctly, motion evolves) plus **artifacts** (vertical stretch from missing cell-aspect correction, wrong invert on a light bg, clipped grid, FOUC before the monospace font loads — fonts settle the cell metrics, so wait). Any headless tool works:
|
||||
|
||||
```bash
|
||||
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/ascii.html?t=1000" frame-mid.png
|
||||
```
|
||||
|
||||
**Before you finish:**
|
||||
1. Opens standalone — no console errors, CDN (Three.js, if used) loads, monospace font applied.
|
||||
2. `?t=N` renders one deterministic frame (injected time + fixed seed), no live loop.
|
||||
3. Screenshotted at 3 simulated times — matches the brief, no vertical stretch or wrong-invert.
|
||||
4. `prefers-reduced-motion` honored — stop/slow the rAF loop, show a static frame.
|
||||
5. Easing is intentional — frame rate throttled on purpose (12–24fps for retro feel), ramp ordering deliberate.
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Need | Approach |
|
||||
|------|----------|
|
||||
| Simple generative field | `<pre>` + `textContent`, sine/noise → ramp |
|
||||
| Photo fidelity | 70-level Bourke ramp, luminance from sRGB weights |
|
||||
| Per-char color / 60fps | Canvas `fillText` per cell |
|
||||
| Video | `<video>` → offscreen canvas → `getImageData` per frame |
|
||||
| 3D scene | Three.js `AsciiEffect.render(scene, camera)` |
|
||||
| Terminal | ANSI `\x1b[H` home + throttle 12–24fps, hide cursor |
|
||||
| Aspect fix | `rows = cols * imgAspect * 0.5` |
|
||||
|
||||
## Reference files
|
||||
|
||||
- `references/rendering.md` — Full brightness ramp tables (10/70/extended), pixel sampling math and cell aspect correction, `<pre>` vs canvas tradeoffs with code, ANSI terminal frame loop with truecolor, and complete `AsciiEffect` wiring.
|
||||
- `scripts/img-to-ascii.mjs` — Runnable Node script that converts a PNG/JPG file to ASCII text, with `--cols`, `--invert`, and `--ramp` flags.
|
||||
@@ -0,0 +1,194 @@
|
||||
# ASCII Rendering Reference
|
||||
|
||||
Detailed tables, sampling math, and complete renderers for ASCII animation.
|
||||
|
||||
## Brightness ramp tables
|
||||
|
||||
Order is **dark → light**. Index into the ramp with `Math.round(lum * (ramp.length - 1))` where `lum` is 0..1.
|
||||
|
||||
### 10-level (compact, generative)
|
||||
```
|
||||
.:-=+*#%@
|
||||
```
|
||||
Good for low-resolution generative fields and terminals. Distinct steps, low banding artifacts.
|
||||
|
||||
### 70-level Paul Bourke ramp (photo fidelity)
|
||||
```
|
||||
$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'.
|
||||
```
|
||||
This is ordered **light → dark** (densest first). For luminance mapping, either reverse the string or use `index = Math.round((1 - lum) * (len - 1))`. Best results for grayscale photos; whitespace at the end represents black/empty.
|
||||
|
||||
### 16-level extended (balance)
|
||||
```
|
||||
.'`,^:";~-_+<>i!lI?/\|()1{}[]rcvunxzjftLCJUYXZO0Qoahkbdpqwm*WMB8&%$#@
|
||||
```
|
||||
Truncate or downsample to taste. For UI/loaders a hand-picked 8–12 char ramp usually looks cleaner than a 70-char ramp because the steps are visually distinct.
|
||||
|
||||
### Block / shade characters (Unicode, smoother gradient)
|
||||
```
|
||||
░▒▓█
|
||||
```
|
||||
Or with the 1/8 block fills for vertical bars: `▁▂▃▄▅▆▇█`. Renders as a near-continuous gradient in monospace fonts; great for waveforms, meters, and smooth fades. Requires a font with box-drawing glyphs (most monospace fonts have them).
|
||||
|
||||
## Luminance computation
|
||||
|
||||
Perceptual (sRGB-weighted, recommended):
|
||||
```js
|
||||
const lum = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255; // 0..1
|
||||
```
|
||||
Fast average (acceptable for stylized output):
|
||||
```js
|
||||
const lum = (r + g + b) / (3 * 255);
|
||||
```
|
||||
Invert for dark-on-light surfaces: `lum = 1 - lum`. Apply gamma to spread midtones: `lum = Math.pow(lum, 0.8)` (lower exponent brightens).
|
||||
|
||||
## Pixel sampling and cell aspect correction
|
||||
|
||||
Monospace cells are about twice as tall as wide. Real cell aspect depends on the font: measure once.
|
||||
|
||||
```js
|
||||
function measureCellAspect(fontFamily = 'monospace', fontPx = 16) {
|
||||
const cv = document.createElement('canvas');
|
||||
const ctx = cv.getContext('2d');
|
||||
ctx.font = `${fontPx}px ${fontFamily}`;
|
||||
const w = ctx.measureText('M').width; // glyph advance width
|
||||
const h = fontPx * 1.0; // with line-height: 1
|
||||
return w / h; // ~0.5 for most fonts
|
||||
}
|
||||
```
|
||||
|
||||
Compute the character grid for a source image, correcting aspect so the picture is not vertically stretched:
|
||||
```js
|
||||
function gridSize(imgW, imgH, cols, cellAspect = 0.5) {
|
||||
const rows = Math.round(cols * (imgH / imgW) * cellAspect);
|
||||
return { cols, rows };
|
||||
}
|
||||
```
|
||||
Draw the source into an offscreen canvas at exactly `cols × rows`, then read all pixels once with `getImageData(0, 0, cols, rows)`. One `getImageData` call per frame is far cheaper than per-pixel reads.
|
||||
|
||||
## `<pre>` vs canvas
|
||||
|
||||
| Aspect | `<pre>` + textContent | Canvas `fillText` |
|
||||
|--------|----------------------|-------------------|
|
||||
| Setup | trivial, one string | per-cell draw loop |
|
||||
| Color | single color (or per-span, slow) | per-char color cheap |
|
||||
| Max size | ~120×60 @ 30fps | thousands of cells @ 60fps |
|
||||
| Selectable text | yes | no |
|
||||
| Best for | generative fields, loaders | video, per-char color, large grids |
|
||||
|
||||
`<pre>` styling that avoids gaps and stretching:
|
||||
```css
|
||||
pre { font-family: ui-monospace, monospace; line-height: 1; letter-spacing: 0;
|
||||
margin: 0; white-space: pre; }
|
||||
```
|
||||
|
||||
Canvas per-char color renderer:
|
||||
```js
|
||||
function drawAsciiCanvas(ctx, chars, colors, cols, rows, cellW, cellH) {
|
||||
ctx.clearRect(0, 0, cols * cellW, rows * cellH);
|
||||
ctx.textBaseline = 'top';
|
||||
ctx.font = `${cellH}px monospace`;
|
||||
for (let y = 0; y < rows; y++) {
|
||||
for (let x = 0; x < cols; x++) {
|
||||
const i = y * cols + x;
|
||||
ctx.fillStyle = colors[i]; // e.g. `rgb(r,g,b)`
|
||||
ctx.fillText(chars[i], x * cellW, y * cellH);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## ANSI terminal frame loop (Node)
|
||||
|
||||
```js
|
||||
const ESC = '\x1b[';
|
||||
const out = process.stdout;
|
||||
|
||||
function start(render, fps = 20) {
|
||||
out.write(ESC + '?25l'); // hide cursor
|
||||
out.write(ESC + '2J'); // clear screen once
|
||||
const interval = 1000 / fps;
|
||||
let start = Date.now();
|
||||
const id = setInterval(() => {
|
||||
const t = Date.now() - start;
|
||||
out.write(ESC + 'H'); // home (cheap, no full clear)
|
||||
out.write(render(t, out.columns || 80, out.rows || 24));
|
||||
}, interval);
|
||||
const stop = () => {
|
||||
clearInterval(id);
|
||||
out.write(ESC + '0m' + ESC + '?25h' + ESC + '2J' + ESC + 'H');
|
||||
process.exit(0);
|
||||
};
|
||||
process.on('SIGINT', stop);
|
||||
return stop;
|
||||
}
|
||||
|
||||
// Truecolor per character: foreground `\x1b[38;2;R;G;Bm`, reset `\x1b[0m`.
|
||||
function colored(ch, r, g, b) {
|
||||
return `${ESC}38;2;${r};${g};${b}m${ch}${ESC}0m`;
|
||||
}
|
||||
|
||||
// Example: plasma using full terminal size
|
||||
start((t, cols, rows) => {
|
||||
const ramp = ' .:-=+*#%@';
|
||||
let s = '';
|
||||
for (let y = 0; y < rows - 1; y++) {
|
||||
for (let x = 0; x < cols; x++) {
|
||||
const v = Math.sin(x * 0.15 + t * 0.001)
|
||||
+ Math.sin(y * 0.25 + t * 0.0015)
|
||||
+ Math.sin((x + y) * 0.1 + t * 0.0008);
|
||||
const lum = (v + 3) / 6;
|
||||
s += ramp[Math.round(lum * (ramp.length - 1))];
|
||||
}
|
||||
s += '\n';
|
||||
}
|
||||
return s;
|
||||
});
|
||||
```
|
||||
Notes: writing `ESC + 'H'` (home) and overwriting is much smoother than clearing the screen every frame, which causes flicker. Avoid printing a trailing newline on the last row or the terminal scrolls. `out.columns`/`out.rows` give the live terminal size; recompute the grid on `process.stdout.on('resize', ...)`.
|
||||
|
||||
## Three.js AsciiEffect — complete wiring
|
||||
|
||||
```js
|
||||
import * as THREE from 'three';
|
||||
import { AsciiEffect } from 'three/addons/effects/AsciiEffect.js';
|
||||
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
|
||||
|
||||
const renderer = new THREE.WebGLRenderer();
|
||||
renderer.setSize(innerWidth, innerHeight);
|
||||
|
||||
const effect = new AsciiEffect(renderer, ' .:-=+*#%@', { invert: true, resolution: 0.2 });
|
||||
effect.setSize(innerWidth, innerHeight);
|
||||
effect.domElement.style.color = 'white';
|
||||
effect.domElement.style.backgroundColor = 'black';
|
||||
document.body.appendChild(effect.domElement); // append the EFFECT's DOM, not renderer.domElement
|
||||
|
||||
const scene = new THREE.Scene();
|
||||
const camera = new THREE.PerspectiveCamera(70, innerWidth / innerHeight, 1, 1000);
|
||||
camera.position.z = 4;
|
||||
scene.add(new THREE.PointLight(0xffffff, 3).position.set(5, 5, 5));
|
||||
scene.add(new THREE.AmbientLight(0x808080));
|
||||
const mesh = new THREE.Mesh(
|
||||
new THREE.TorusKnotGeometry(1, 0.3, 100, 16),
|
||||
new THREE.MeshStandardMaterial({ flatShading: true })
|
||||
);
|
||||
scene.add(mesh);
|
||||
|
||||
const controls = new OrbitControls(camera, effect.domElement); // attach to effect DOM
|
||||
|
||||
function animate(t) {
|
||||
mesh.rotation.y = t * 0.0005;
|
||||
effect.render(scene, camera); // render through the effect
|
||||
requestAnimationFrame(animate);
|
||||
}
|
||||
requestAnimationFrame(animate);
|
||||
|
||||
addEventListener('resize', () => {
|
||||
camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix();
|
||||
effect.setSize(innerWidth, innerHeight);
|
||||
});
|
||||
```
|
||||
Key gotchas: append `effect.domElement` (not the renderer's canvas) and call `effect.render`, not `renderer.render`. `resolution` (default ~0.15) controls character density; lower = fewer, larger characters. Lighting matters — ASCII reads luminance, so use strong directional contrast and `flatShading` for crisp edges.
|
||||
|
||||
---
|
||||
Map brightness to the right glyph ramp and the characters come alive. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=ascii-animation)** — the AI motion agent for editable, on-brand motion graphics.
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env node
|
||||
// img-to-ascii.mjs — Convert a PNG/JPG image to ASCII text.
|
||||
//
|
||||
// Usage:
|
||||
// node img-to-ascii.mjs <image> [--cols 120] [--invert] [--ramp " .:-=+*#%@"]
|
||||
//
|
||||
// Dependency: sharp (npm i sharp). Sharp decodes PNG/JPG/WebP and resizes.
|
||||
//
|
||||
// Notes:
|
||||
// - Applies monospace cell-aspect correction (cells are ~2x taller than wide),
|
||||
// so rows = cols * (imgH/imgW) * 0.5.
|
||||
// - Luminance uses sRGB perceptual weights (0.2126/0.7152/0.0722).
|
||||
|
||||
import sharp from 'sharp';
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = { cols: 120, invert: false, ramp: ' .:-=+*#%@', file: null };
|
||||
for (let i = 2; i < argv.length; i++) {
|
||||
const a = argv[i];
|
||||
if (a === '--cols') args.cols = parseInt(argv[++i], 10);
|
||||
else if (a === '--invert') args.invert = true;
|
||||
else if (a === '--ramp') args.ramp = argv[++i];
|
||||
else if (!a.startsWith('--')) args.file = a;
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const { cols, invert, ramp, file } = parseArgs(process.argv);
|
||||
if (!file) {
|
||||
console.error('Usage: node img-to-ascii.mjs <image> [--cols N] [--invert] [--ramp "..."]');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const CELL_ASPECT = 0.5; // monospace width:height
|
||||
const meta = await sharp(file).metadata();
|
||||
const rows = Math.max(1, Math.round(cols * (meta.height / meta.width) * CELL_ASPECT));
|
||||
|
||||
// Resize to the character grid, drop alpha, get raw RGB bytes.
|
||||
const { data } = await sharp(file)
|
||||
.resize(cols, rows, { fit: 'fill' })
|
||||
.removeAlpha()
|
||||
.raw()
|
||||
.toBuffer({ resolveWithObject: true });
|
||||
|
||||
const last = ramp.length - 1;
|
||||
const lines = [];
|
||||
for (let y = 0; y < rows; y++) {
|
||||
let line = '';
|
||||
for (let x = 0; x < cols; x++) {
|
||||
const i = (y * cols + x) * 3;
|
||||
let lum = (0.2126 * data[i] + 0.7152 * data[i + 1] + 0.0722 * data[i + 2]) / 255;
|
||||
if (invert) lum = 1 - lum;
|
||||
line += ramp[Math.round(lum * last)];
|
||||
}
|
||||
lines.push(line);
|
||||
}
|
||||
process.stdout.write(lines.join('\n') + '\n');
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('Error:', err.message);
|
||||
process.exit(1);
|
||||
});
|
||||
Whitespace-only changes.
@@ -0,0 +1,177 @@
|
||||
---
|
||||
name: glassmorphism
|
||||
description: This skill should be used when the user asks to "add a glassmorphism effect", "frosted glass UI", "Apple liquid glass style", "frosted blur card", "translucent glass panel animation", "make a frosted nav bar", "build a glass modal/dialog", "animate a glass card on hover", or "add a refracting liquid-glass hero". Covers frosted translucent panels with backdrop-filter blur, edge/specular highlights, SVG liquid-glass refraction, motion on hover/scroll/enter, and accessible reduced-transparency fallbacks.
|
||||
version: 0.1.0
|
||||
---
|
||||
|
||||
# Glassmorphism (Frosted & Liquid Glass)
|
||||
|
||||
Translucent, frosted UI: panels you can see through, blurred so the backdrop reads as soft color, rimmed by a bright edge of light, floating on layered shadow. The 2026 "liquid glass" evolution adds refraction — the background visibly bends through the panel — plus moving specular highlights. The goal is depth and material, not just opacity.
|
||||
|
||||
## When to use
|
||||
|
||||
- Frosted cards, nav bars, sidebars, modals/dialogs, and toolbars over busy/photo backgrounds
|
||||
- Login/hero panels and overlays that should feel layered above the page
|
||||
- Apple-style "liquid glass" heroes: refracting, slowly churning surfaces with a specular sweep
|
||||
- Hover/scroll/enter motion on glass — frost deepening, highlight brightening, the panel lifting
|
||||
- Any place where content needs to read as floating glass while staying legible
|
||||
|
||||
## The four ingredients of believable glass
|
||||
|
||||
Glass is never one property. Every panel needs all four, or it reads as a plain translucent box:
|
||||
|
||||
1. **Frost** — `backdrop-filter: blur()` plus `saturate()` to keep backdrop color vivid through the blur.
|
||||
2. **Translucency** — a `background` with alpha (~0.08–0.18), never fully opaque, never fully clear.
|
||||
3. **Edge of glass** — a hairline border *brighter* than the fill, ideally a lit top-left → dim bottom-right highlight, so the rim catches light.
|
||||
4. **Depth** — layered `box-shadow`: an ambient drop shadow to float it, plus an `inset` top highlight and bottom shade to round the surface.
|
||||
|
||||
```css
|
||||
.glass {
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
backdrop-filter: blur(16px) saturate(160%);
|
||||
-webkit-backdrop-filter: blur(16px) saturate(160%); /* Safari needs the prefix */
|
||||
border-radius: 20px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.25);
|
||||
box-shadow:
|
||||
0 8px 32px rgba(0, 0, 0, 0.25), /* float */
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.35), /* top highlight */
|
||||
inset 0 -1px 0 rgba(0, 0, 0, 0.12); /* bottom shade */
|
||||
}
|
||||
```
|
||||
|
||||
Frost tiers: light UI chrome `blur(8–12px)` / alpha `0.08–0.14`; heavy modal/login `blur(24–40px)` / alpha `0.10–0.18`. Dark glass: fill `rgba(0,0,0,0.3)`, softer top highlight.
|
||||
|
||||
**`backdrop-filter` only blurs content that sits behind the element.** Over a flat background color it does nothing visible — glass needs a busy backdrop (image, gradient, video) to frost.
|
||||
|
||||
## Specular edge highlight and anti-banding grain
|
||||
|
||||
A flat border is dead. Draw a masked 1px ring with a lit corner via `::before`, and dither away gradient **banding** (stepped contour lines under heavy blur) with a faint `feTurbulence` noise overlay via `::after` at `opacity ≤ 0.06`. Full masked-border and inline-noise recipes are in `references/glass-recipes.md`.
|
||||
|
||||
## Motion: animate the glass, not the geometry
|
||||
|
||||
Animate the *qualities* of the glass — frost deepening, highlight brightening, the panel lifting — so it reads as the surface "leaning into the light."
|
||||
|
||||
```css
|
||||
.glass {
|
||||
transition: backdrop-filter .4s ease, background .4s ease,
|
||||
box-shadow .4s ease, transform .4s cubic-bezier(.16,1,.3,1);
|
||||
}
|
||||
.glass:hover {
|
||||
backdrop-filter: blur(24px) saturate(180%);
|
||||
background: rgba(255,255,255,.18);
|
||||
transform: translateY(-4px);
|
||||
box-shadow: 0 16px 48px rgba(0,0,0,.3), inset 0 1px 0 rgba(255,255,255,.5);
|
||||
}
|
||||
```
|
||||
|
||||
- **Entrance** (frost resolving from clear): pair a `[data-enter]` transition with `@starting-style { backdrop-filter: blur(0); opacity: 0; transform: translateY(16px) }`.
|
||||
- **Specular sweep**: a skewed white gradient animated across the surface on hover or as a slow ambient loop.
|
||||
- **Caveat**: animating the blur *radius* is the most expensive thing here — the backdrop is re-blurred every frame. If hover janks, animate `transform`/`box-shadow`/`background` (cheap) and keep the blur delta small or snap it.
|
||||
|
||||
## Liquid glass — SVG refraction (the 2026 look)
|
||||
|
||||
Bend the background through the panel like a thick lens: drive `feDisplacementMap` from animated `feTurbulence`, applied via `filter` (it distorts the element's own pixels) layered over a `backdrop-filter` frost.
|
||||
|
||||
```html
|
||||
<svg width="0" height="0" style="position:absolute"><filter id="liquid-glass">
|
||||
<feTurbulence type="fractalNoise" baseFrequency="0.008 0.012" numOctaves="2" seed="3" result="n">
|
||||
<animate attributeName="baseFrequency" dur="18s"
|
||||
values="0.008 0.012;0.012 0.008;0.008 0.012" repeatCount="indefinite"/>
|
||||
</feTurbulence>
|
||||
<feDisplacementMap in="SourceGraphic" in2="n" scale="22" xChannelSelector="R" yChannelSelector="G"/>
|
||||
</filter></svg>
|
||||
```
|
||||
|
||||
`scale` = refraction strength (8–14 subtle, 20–30 pronounced, >40 molten). Lower `baseFrequency` = larger, slower waves (more liquid). Keep the `animate` `dur` long (12–20s) so it breathes. These filters are heavy — use on **one** hero element, not a grid.
|
||||
|
||||
## Performance — backdrop-filter is expensive
|
||||
|
||||
- Each glass element re-samples and blurs everything behind it. **Limit the count**; a dozen on screen tanks scroll FPS.
|
||||
- Promote heavy glass to its own layer (`transform: translateZ(0)` or `will-change: transform`), and remove `will-change` after the animation.
|
||||
- Don't stack `backdrop-filter` elements over each other — nested blur re-blurs the blur (quadratic cost).
|
||||
- Big radii (>40px) over large areas are the worst case; cap radius and panel size.
|
||||
|
||||
## Accessibility — non-negotiable
|
||||
|
||||
Glass is decoration; content must stay legible and the effect must be defeatable.
|
||||
|
||||
```css
|
||||
@media (prefers-reduced-transparency: reduce) {
|
||||
.glass { background: #1a1a2e; backdrop-filter: none; -webkit-backdrop-filter: none; }
|
||||
.glass::after { display: none; } /* drop grain */
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.glass { transition: none; }
|
||||
.liquid { filter: none; } /* stop the refraction churn */
|
||||
}
|
||||
@supports not (backdrop-filter: blur(1px)) {
|
||||
.glass { background: rgba(30,30,50,.85); } /* opaque-enough fallback */
|
||||
}
|
||||
```
|
||||
|
||||
**Contrast over busy backgrounds**: translucent panels over photos can drop text below WCAG. Add a semi-opaque scrim or darkening gradient *under* the text, optionally `text-shadow: 0 1px 2px rgba(0,0,0,.4)`, and verify ≥ 4.5:1 body / ≥ 3:1 large against the *brightest* region of the backdrop.
|
||||
|
||||
## Deliver & verify (standalone HTML)
|
||||
|
||||
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
|
||||
|
||||
For a self-contained glass demo (card, nav, modal, liquid-glass hero) the deliverable is **one HTML file that opens directly in a browser** — markup, CSS, and (if liquid) one inline SVG filter, no build step. A single file is the right tier for a glass surface; don't reach for a bundler. The panel **must overlap a real backdrop** (drop in a photo or gradient) or there is nothing to frost and the demo lies.
|
||||
|
||||
**Output contract:**
|
||||
- One `.html` file: a busy backdrop, your glass markup, the CSS (frost + edge highlight + grain + shadows), and any inline SVG `feDisplacementMap` filter.
|
||||
- A way to land on the **resolved state** *and* a **frozen frame** of any loop — glass verifies by both state (rest/hover/enter) and time (the sweep/refraction).
|
||||
- Include the freeze harness below so any moment can be pinned for inspection.
|
||||
|
||||
**Seek harness — pin a deterministic state + frame.** `?state=hover` forces the hover look; `?t=N` freezes CSS animations and the SVG refraction at `N` seconds, so a screenshot lands on a still, deterministic frame:
|
||||
|
||||
```html
|
||||
<script>
|
||||
const p = new URLSearchParams(location.search);
|
||||
const state = p.get("state");
|
||||
if (state) document.documentElement.dataset.state = state; // CSS keys off :root[data-state="hover"]
|
||||
const t = p.get("t");
|
||||
if (t !== null) {
|
||||
document.getAnimations().forEach(a => { a.currentTime = parseFloat(t)*1000; a.pause(); }); // freeze CSS sweep
|
||||
const svg = document.querySelector("svg");
|
||||
svg?.pauseAnimations?.(); svg?.setCurrentTime?.(parseFloat(t)); // freeze refraction
|
||||
}
|
||||
window.__ready = true;
|
||||
</script>
|
||||
```
|
||||
|
||||
**Verify loop — render → set state/freeze → screenshot → check:** open each meaningful state (`?state=rest`, `?state=hover`) and a frozen loop frame (`?t=2`), screenshot, and confirm the glass **reads as glass** — blur and edge highlight visibly present, no color banding, text contrast holds over the backdrop — plus check **artifacts** (flat box because the backdrop is plain color, missing `-webkit-` prefix in Safari, refraction too strong/molten, jank from animating blur). Then load `prefers-reduced-transparency` and confirm the **solid fallback renders** legibly. Any headless tool works:
|
||||
|
||||
```bash
|
||||
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/glass.html?state=hover" hover.png
|
||||
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/glass.html?t=2" loop.png
|
||||
```
|
||||
|
||||
To check the fallback headlessly, emulate the media feature (e.g. Playwright `--color-scheme`-style flags, or a `?reduced=1` query that toggles a class mirroring the media query) and screenshot that the panel is solid and readable.
|
||||
|
||||
**Before you finish:**
|
||||
1. Opens standalone — no console errors; the glass overlaps a real busy backdrop, not a flat color.
|
||||
2. Reads as glass — blur + bright edge highlight both visible, layered shadow floats it, no banding (grain present).
|
||||
3. Text contrast holds over the brightest part of the backdrop (≥ 4.5:1 body).
|
||||
4. `?state=` / `?t=N` freeze lands a deterministic, settled frame.
|
||||
5. `prefers-reduced-transparency` → solid opaque panel; `prefers-reduced-motion` → refraction/sweep stopped; `@supports` fallback for no `backdrop-filter`.
|
||||
6. Performance sane — glass count limited, blur not animated on a janky path, liquid refraction on one element only.
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Need | Approach |
|
||||
|------|----------|
|
||||
| Base frost | `backdrop-filter: blur(16px) saturate(160%)` + alpha bg |
|
||||
| Edge of glass | brighter `border` + masked `::before` lit-corner ring |
|
||||
| Float / depth | `box-shadow` drop + `inset` top highlight & bottom shade |
|
||||
| Kill banding | `feTurbulence` noise `::after`, `opacity ≤ .06` |
|
||||
| Hover motion | transition `transform`/`box-shadow`/`background`, small blur delta |
|
||||
| Entrance | `@starting-style { backdrop-filter: blur(0); opacity:0 }` |
|
||||
| Liquid refraction | `feDisplacementMap` ← animated `feTurbulence`, via `filter` |
|
||||
| Specular sweep | skewed white gradient animated across surface |
|
||||
| Safari | always pair `-webkit-backdrop-filter` |
|
||||
| Reduced transparency | solid opaque panel, drop grain |
|
||||
| No backdrop-filter | `@supports not (...)` opaque-enough fallback |
|
||||
|
||||
## Reference files
|
||||
|
||||
- `references/glass-recipes.md` — full copy-paste recipes: base glass card with tiers, the masked specular edge ring, anti-banding grain, hover/enter/scroll motion, the specular sweep, the SVG `feDisplacementMap`/`feTurbulence` liquid-glass filter with tuning knobs, performance rules, the reduced-transparency/reduced-motion/`@supports` fallbacks, contrast defenses, and the standalone freeze harness.
|
||||
@@ -0,0 +1,242 @@
|
||||
# Glassmorphism Recipes
|
||||
|
||||
Copy-paste recipes for frosted translucent panels, the "edge of glass" highlight, animated liquid-glass refraction, and the reduced-transparency fallback. All standalone CSS + optional inline SVG — no build step.
|
||||
|
||||
## 1. The base glass card
|
||||
|
||||
The four ingredients of believable glass: **blur** (frost), **translucency** (you see through it), **edge highlight** (light catches the rim), **layered shadow** (it floats). Plus a touch of `saturate()` so the backdrop reads vivid through the frost.
|
||||
|
||||
```css
|
||||
.glass {
|
||||
/* translucency — never fully opaque, never fully clear */
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
/* frost: blur the backdrop, lift saturation so color survives the blur */
|
||||
backdrop-filter: blur(16px) saturate(160%);
|
||||
-webkit-backdrop-filter: blur(16px) saturate(160%); /* Safari still needs the prefix */
|
||||
border-radius: 20px;
|
||||
/* edge of glass: a hairline border slightly brighter than the fill */
|
||||
border: 1px solid rgba(255, 255, 255, 0.25);
|
||||
/* depth: ambient drop + a top inner highlight + a bottom inner shade */
|
||||
box-shadow:
|
||||
0 8px 32px rgba(0, 0, 0, 0.25),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.35),
|
||||
inset 0 -1px 0 rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
```
|
||||
|
||||
Tuning by tier:
|
||||
- **Light frost** (UI chrome over content): `blur(8–12px)`, alpha `0.08–0.14`.
|
||||
- **Heavy frost** (modal scrim, login card): `blur(24–40px)`, alpha `0.10–0.18`.
|
||||
- Dark glass: swap the fill to `rgba(0,0,0,0.3)` and the top inner highlight to a softer white.
|
||||
|
||||
`backdrop-filter` only has anything to blur if there is content **behind** the element — it must overlap a busy background (image, gradient, video). On a flat color it looks like a plain translucent box.
|
||||
|
||||
## 2. The specular edge highlight (the rim of light)
|
||||
|
||||
A single border is flat. Real glass catches a bright sweep along the top-left edge and falls off. Layer a soft conic/linear highlight via a pseudo-element with a masked border.
|
||||
|
||||
```css
|
||||
.glass {
|
||||
position: relative;
|
||||
isolation: isolate; /* keep the highlight blend local */
|
||||
}
|
||||
.glass::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: inherit;
|
||||
padding: 1px; /* border thickness */
|
||||
background: linear-gradient(
|
||||
135deg,
|
||||
rgba(255, 255, 255, 0.7),
|
||||
rgba(255, 255, 255, 0) 40%,
|
||||
rgba(255, 255, 255, 0) 60%,
|
||||
rgba(255, 255, 255, 0.25)
|
||||
);
|
||||
/* mask trick: show only the 1px ring, punch out the interior */
|
||||
-webkit-mask:
|
||||
linear-gradient(#000 0 0) content-box,
|
||||
linear-gradient(#000 0 0);
|
||||
-webkit-mask-composite: xor;
|
||||
mask-composite: exclude;
|
||||
pointer-events: none;
|
||||
}
|
||||
```
|
||||
|
||||
This gives the panel a lit top-left corner and a dim bottom-right, the cue the brain reads as "curved glass under a light."
|
||||
|
||||
## 3. Kill banding with grain
|
||||
|
||||
Heavy `blur()` over a smooth gradient produces visible color **banding** (stepped contour lines). A faint noise overlay dithers it away.
|
||||
|
||||
```css
|
||||
.glass::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: inherit;
|
||||
pointer-events: none;
|
||||
opacity: 0.04; /* barely there */
|
||||
mix-blend-mode: overlay;
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='120'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
|
||||
}
|
||||
```
|
||||
|
||||
`feTurbulence` generates the noise tile inline — no asset file. Keep opacity ≤ 0.06 or it reads as texture, not dither.
|
||||
|
||||
## 4. Motion: animate the glass on hover / enter / scroll
|
||||
|
||||
Animate the *qualities* of the glass, not its geometry. Frost deepening and the highlight brightening on hover reads as the panel "leaning into the light."
|
||||
|
||||
```css
|
||||
.glass {
|
||||
transition:
|
||||
backdrop-filter 0.4s ease,
|
||||
background 0.4s ease,
|
||||
box-shadow 0.4s ease,
|
||||
transform 0.4s cubic-bezier(0.16, 1, 0.3, 1);
|
||||
}
|
||||
.glass:hover {
|
||||
backdrop-filter: blur(24px) saturate(180%);
|
||||
background: rgba(255, 255, 255, 0.18);
|
||||
transform: translateY(-4px);
|
||||
box-shadow:
|
||||
0 16px 48px rgba(0, 0, 0, 0.3),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
```
|
||||
|
||||
Caveat: animating `backdrop-filter` itself is the most expensive thing here — the backdrop is re-sampled and re-blurred every frame. If hover feels janky, animate only `transform` + `box-shadow` + `background` (cheaper) and snap the blur, or keep the blur change small.
|
||||
|
||||
**Entrance** (frost resolving in) reads beautifully with `@starting-style`:
|
||||
|
||||
```css
|
||||
.glass[data-enter] {
|
||||
transition: opacity 0.5s ease, backdrop-filter 0.6s ease, transform 0.5s ease;
|
||||
}
|
||||
@starting-style {
|
||||
.glass[data-enter] {
|
||||
opacity: 0;
|
||||
backdrop-filter: blur(0px) saturate(100%);
|
||||
transform: translateY(16px) scale(0.98);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Specular sweep** — a moving glint across the surface on hover or as an ambient loop:
|
||||
|
||||
```css
|
||||
.glass .sweep {
|
||||
position: absolute; inset: 0; border-radius: inherit; overflow: hidden; pointer-events: none;
|
||||
}
|
||||
.glass .sweep::before {
|
||||
content: ""; position: absolute; top: 0; left: -60%; width: 50%; height: 100%;
|
||||
background: linear-gradient(105deg, transparent, rgba(255,255,255,0.35), transparent);
|
||||
transform: skewX(-15deg);
|
||||
animation: sweep 4s ease-in-out infinite;
|
||||
}
|
||||
@keyframes sweep { 0%,100% { left: -60%; } 50% { left: 110%; } }
|
||||
```
|
||||
|
||||
## 5. Liquid glass — SVG refraction (the 2026 look)
|
||||
|
||||
Apple-style "liquid glass" bends the background as if seen through a thick, wobbling lens. Drive a `feDisplacementMap` from animated `feTurbulence` and apply it via `filter` (note: `filter`, not `backdrop-filter` — it distorts the element's own rendered content; layer it over a `backdrop-filter` frost for the full effect).
|
||||
|
||||
```html
|
||||
<svg width="0" height="0" style="position:absolute">
|
||||
<filter id="liquid-glass">
|
||||
<feTurbulence type="fractalNoise" baseFrequency="0.008 0.012"
|
||||
numOctaves="2" seed="3" result="noise">
|
||||
<!-- animate the field so the refraction slowly churns -->
|
||||
<animate attributeName="baseFrequency"
|
||||
dur="18s" values="0.008 0.012; 0.012 0.008; 0.008 0.012"
|
||||
repeatCount="indefinite"/>
|
||||
</feTurbulence>
|
||||
<feDisplacementMap in="SourceGraphic" in2="noise"
|
||||
scale="22" xChannelSelector="R" yChannelSelector="G"/>
|
||||
</filter>
|
||||
</svg>
|
||||
```
|
||||
|
||||
```css
|
||||
.liquid {
|
||||
backdrop-filter: blur(6px) saturate(150%); /* light frost under the refraction */
|
||||
filter: url(#liquid-glass); /* the lens distortion */
|
||||
}
|
||||
```
|
||||
|
||||
Knobs:
|
||||
- `scale` on `feDisplacementMap` = refraction strength. 8–14 = subtle ripple; 20–30 = pronounced lens; >40 = molten.
|
||||
- Lower `baseFrequency` = larger, slower waves (more "liquid"); higher = tight, busy ripples.
|
||||
- Animate `baseFrequency` (above) or `scale` for a living surface. Keep `dur` long (12–20s) so it breathes rather than shimmers.
|
||||
|
||||
Cost warning: SVG displacement filters are heavy and force off-GPU paths in some browsers. Use on **one** hero element, not a grid of cards. Test on a mid-range laptop; drop to plain `backdrop-filter` if frames stutter.
|
||||
|
||||
## 6. Performance — backdrop-filter is expensive
|
||||
|
||||
- Each `backdrop-filter` element re-samples and blurs everything behind it. **Limit the count** — a dozen glass cards on screen will tank scroll FPS.
|
||||
- Promote heavy glass to its own compositor layer: `transform: translateZ(0)` or `will-change: transform` (remove `will-change` after the animation; leaving it on wastes memory).
|
||||
- Avoid stacking `backdrop-filter` elements over each other (nested blur re-blurs the blur — quadratic cost).
|
||||
- Prefer animating `transform`/`opacity`/`box-shadow` over animating the blur radius. If you must animate blur, keep the radius delta small.
|
||||
- Big blur radii (>40px) over large areas are the single worst case; cap the radius and the panel size.
|
||||
|
||||
## 7. Accessibility — non-negotiable
|
||||
|
||||
Glass is decorative; the content on it must stay legible and the effect must be defeatable.
|
||||
|
||||
**Honor reduced transparency and reduced motion** — fall back to a solid, opaque panel:
|
||||
|
||||
```css
|
||||
@media (prefers-reduced-transparency: reduce) {
|
||||
.glass {
|
||||
background: #1a1a2e; /* solid, accessible panel */
|
||||
backdrop-filter: none;
|
||||
-webkit-backdrop-filter: none;
|
||||
border-color: rgba(255, 255, 255, 0.15);
|
||||
}
|
||||
.glass::after { display: none; } /* drop grain/noise */
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.glass, .glass .sweep::before { transition: none; animation: none; }
|
||||
.liquid { filter: none; } /* stop the churning refraction */
|
||||
}
|
||||
```
|
||||
|
||||
**Contrast over busy backgrounds.** Translucent panels over photos can drop text below WCAG contrast. Defenses:
|
||||
- Put a contrast floor *under* the text: a semi-opaque scrim or a darkening gradient inside the panel.
|
||||
- Add `text-shadow: 0 1px 2px rgba(0,0,0,0.4)` to body text on glass.
|
||||
- Target ≥ 4.5:1 for body text, ≥ 3:1 for large text — and verify against the *brightest* region of the backdrop, not the average.
|
||||
|
||||
**Feature fallback** for browsers without `backdrop-filter`:
|
||||
|
||||
```css
|
||||
@supports not (backdrop-filter: blur(1px)) {
|
||||
.glass { background: rgba(30, 30, 50, 0.85); } /* opaque-enough fallback */
|
||||
}
|
||||
```
|
||||
|
||||
## 8. Standalone freeze harness
|
||||
|
||||
Glass demos verify by *state* (rest / hover / enter) and *time* (the sweep/refraction loop). Wire both so a screenshot lands deterministically:
|
||||
|
||||
```html
|
||||
<script>
|
||||
const p = new URLSearchParams(location.search);
|
||||
const state = p.get("state"); // ?state=hover → force the hover look
|
||||
if (state) document.documentElement.dataset.state = state;
|
||||
const t = p.get("t"); // ?t=2 → freeze CSS animations at 2s
|
||||
if (t !== null) {
|
||||
document.getAnimations().forEach(a => { a.currentTime = parseFloat(t) * 1000; a.pause(); });
|
||||
// SVG SMIL (the <animate>): pin the refraction frame too
|
||||
document.querySelector("svg")?.pauseAnimations?.();
|
||||
document.querySelector("svg")?.setCurrentTime?.(parseFloat(t));
|
||||
}
|
||||
window.__ready = true;
|
||||
</script>
|
||||
```
|
||||
|
||||
CSS drives the forced state: `:root[data-state="hover"] .glass { /* hover values */ }`.
|
||||
|
||||
---
|
||||
Frosted glass that reads as glass — blur, edge light, and refraction, with a clean fallback. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=glassmorphism)** — the AI motion agent for editable, on-brand motion graphics.
|
||||
Whitespace-only changes.
@@ -0,0 +1,225 @@
|
||||
---
|
||||
name: gsap-web
|
||||
description: This skill should be used when the user asks to "build a scroll animation", "add ScrollTrigger", "pin a section while scrolling", "scrub an animation to scroll", "create a hero timeline", "do a horizontal scroll section", "split text and animate words", "animate a layout change with GSAP Flip", "sync ScrollTrigger with Lenis", "Lenis smooth scroll jittery", "ScrollTrigger markers drift", "ScrollTrigger pins break with Lenis/Locomotive", or "set up smooth scroll with GSAP pinning". Covers GSAP timelines, ScrollTrigger, SplitText, Flip, and Lenis/Locomotive smooth-scroll sync for code-driven web motion.
|
||||
version: 0.1.0
|
||||
---
|
||||
|
||||
# GSAP for the Web
|
||||
|
||||
GSAP (GreenSock Animation Platform) is the workhorse for code-driven web motion: sequenced timelines, scroll-driven storytelling, text reveals, and layout transitions. As of GSAP 3.12+, every plugin (ScrollTrigger, SplitText, Flip, MotionPath, MorphSVG, Draggable, Observer) is 100% free, including for commercial use.
|
||||
|
||||
## When to use
|
||||
|
||||
- Scroll-driven storytelling: pinned sections, parallax, progress scrubbing, horizontal scroll
|
||||
- Sequenced hero animations and complex multi-element timelines with precise overlap control
|
||||
- Text reveals split into chars/words/lines (SplitText)
|
||||
- Layout transitions where an element changes position/size/parent (Flip)
|
||||
- Any motion needing fine timing control, easing precision, or imperative orchestration
|
||||
|
||||
## Install and register
|
||||
|
||||
```js
|
||||
import gsap from "gsap";
|
||||
import { ScrollTrigger } from "gsap/ScrollTrigger";
|
||||
import { SplitText } from "gsap/SplitText";
|
||||
import { Flip } from "gsap/Flip";
|
||||
|
||||
gsap.registerPlugin(ScrollTrigger, SplitText, Flip);
|
||||
```
|
||||
|
||||
Plugins MUST be registered before use or they silently no-op. With a bundler, register once at app entry.
|
||||
|
||||
## Core techniques
|
||||
|
||||
### Timelines first
|
||||
|
||||
Prefer one timeline over many independent tweens — it gives a single playhead, relative positioning, and easy reversal.
|
||||
|
||||
```js
|
||||
const tl = gsap.timeline({ defaults: { ease: "power3.out", duration: 0.6 } });
|
||||
tl.from(".title", { yPercent: 100, opacity: 0 })
|
||||
.from(".sub", { y: 20, opacity: 0 }, "-=0.3") // start 0.3s before prev ends
|
||||
.from(".cta", { scale: 0.9, opacity: 0 }, "<"); // align to prev tween START
|
||||
```
|
||||
|
||||
Position parameter cheat sheet:
|
||||
- `"+=0.5"` / `"-=0.3"` — relative to the end of the timeline (gap / overlap)
|
||||
- `"<"` — start of the previous tween; `">"` — end of the previous tween
|
||||
- `"<0.2"` — 0.2s after the previous tween's start
|
||||
- `"myLabel"` — at a named label added via `tl.addLabel("myLabel")`
|
||||
|
||||
Use `.from()` for entrances (animates FROM the given values TO current CSS), `.to()` for exits, `.fromTo()` when both ends must be explicit (most robust against re-runs).
|
||||
|
||||
### gsap.to vs set vs quickTo
|
||||
|
||||
```js
|
||||
gsap.set(el, { autoAlpha: 0 }); // instant, no tween (autoAlpha = opacity + visibility)
|
||||
const xTo = gsap.quickTo(el, "x", { duration: 0.4, ease: "power3" });
|
||||
window.addEventListener("pointermove", (e) => xTo(e.clientX)); // fast repeated updates
|
||||
```
|
||||
|
||||
`autoAlpha` is preferred over raw `opacity` because it also toggles `visibility:hidden` at 0, removing the element from hit-testing.
|
||||
|
||||
### ScrollTrigger basics
|
||||
|
||||
```js
|
||||
gsap.to(".panel", {
|
||||
xPercent: -100,
|
||||
ease: "none",
|
||||
scrollTrigger: {
|
||||
trigger: ".wrap",
|
||||
start: "top top", // when trigger top hits viewport top
|
||||
end: "+=2000", // 2000px of scroll distance
|
||||
pin: true, // freeze .wrap while the tween plays
|
||||
scrub: 1, // tie progress to scrollbar (1 = 1s catch-up smoothing)
|
||||
markers: true, // dev-only visual markers — remove for prod
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Key semantics:
|
||||
- `start`/`end` take `"triggerPos viewportPos"` (e.g. `"top center"`) or `"+=px"`.
|
||||
- `scrub: true` locks animation progress to scroll exactly; `scrub: <number>` adds smoothing lag.
|
||||
- `toggleActions: "play pause resume reverse"` controls onEnter/onLeave/onEnterBack/onLeaveBack for non-scrubbed triggers.
|
||||
- Use `ease: "none"` for scrubbed tweens so motion tracks scroll linearly.
|
||||
|
||||
### Smooth scroll (Lenis) + ScrollTrigger
|
||||
|
||||
Pairing Lenis (or Locomotive) smooth scrolling with ScrollTrigger desyncs unless both run on one loop. Lenis smooths scroll on its own rAF while ScrollTrigger reads scroll on GSAP's ticker; when they tick independently ScrollTrigger samples a stale position. The fix: drive Lenis from GSAP's ticker and update ScrollTrigger on every Lenis scroll.
|
||||
|
||||
```js
|
||||
import Lenis from "lenis";
|
||||
|
||||
const lenis = new Lenis({ duration: 1.2, smoothWheel: true });
|
||||
|
||||
lenis.on("scroll", ScrollTrigger.update); // 1. update ScrollTrigger on every Lenis scroll
|
||||
gsap.ticker.add((t) => lenis.raf(t * 1000)); // 2. one loop: ticker drives Lenis (seconds → ms)
|
||||
gsap.ticker.lagSmoothing(0); // 3. stop GSAP catch-up jitter on heavy frames
|
||||
```
|
||||
|
||||
Critical: `gsap.ticker` passes time in **seconds**, `lenis.raf()` wants **milliseconds** — multiply by 1000. Do NOT also run a standalone `requestAnimationFrame(raf)` loop for Lenis; that double-drives it.
|
||||
|
||||
Common bugs:
|
||||
- **Jitter/stutter** — a leftover `requestAnimationFrame(raf)` loop competing with the ticker, or missing `lagSmoothing(0)`. Remove the rogue loop; set lag smoothing to 0.
|
||||
- **Markers drift** from their triggers — `ScrollTrigger.update` is not subscribed to `lenis.on("scroll", …)`.
|
||||
- **Pins break** — under Lenis do NOT set a `scrollerProxy` (it scrolls the document). Under Locomotive you MUST wire `scrollerProxy` + `pinType` and set `scroller:` on every trigger.
|
||||
- **Scroll stuck / flipped direction** — missing the `* 1000` unit conversion, or two loops out of order.
|
||||
|
||||
Cleanup on SPA unmount: `gsap.ticker.remove(update)` + `lenis.destroy()`, else loops stack per navigation. Gate behind `prefers-reduced-motion` (skip Lenis, run native scroll). Full Lenis + Locomotive wiring, anchor-link routing, `data-lenis-prevent`, React (`useGSAP`/`useEffect`), and a symptom→cause table are in `references/scrolltrigger-lenis.md`.
|
||||
|
||||
### SplitText (text reveal)
|
||||
|
||||
```js
|
||||
const split = SplitText.create(".headline", { type: "lines, words", linesClass: "line" });
|
||||
gsap.from(split.lines, { yPercent: 100, opacity: 0, stagger: 0.08, duration: 0.7, ease: "power4.out" });
|
||||
```
|
||||
|
||||
Gotchas:
|
||||
- Wrap line-mask reveals: set `overflow: hidden` on the line wrapper so `yPercent: 100` hides cleanly. Add `autoSplit: true` (GSAP 3.13+) to re-split on font load / resize.
|
||||
- Call `split.revert()` before re-splitting or on unmount to restore original DOM and avoid duplicated nodes.
|
||||
- Always split AFTER web fonts load (`document.fonts.ready.then(...)`) to prevent wrong line breaks.
|
||||
|
||||
### Flip (layout transitions)
|
||||
|
||||
Flip records state, lets the DOM change instantly, then animates the visual difference (FLIP technique). Ideal for grid<->list, expanding cards, and reparenting.
|
||||
|
||||
```js
|
||||
const state = Flip.getState(".item"); // 1. capture BEFORE
|
||||
container.classList.toggle("grid"); // 2. mutate DOM/CSS (instant)
|
||||
Flip.from(state, { // 3. animate the delta
|
||||
duration: 0.6, ease: "power2.inOut", stagger: 0.05,
|
||||
absolute: true, // take items out of flow during move (prevents reflow jitter)
|
||||
});
|
||||
```
|
||||
|
||||
### Easing quick guide
|
||||
|
||||
- `power2/3.out` — entrances (fast then settle)
|
||||
- `power2.inOut` — moves between two on-screen states
|
||||
- `back.out(1.7)` — overshoot/pop (number = overshoot amount)
|
||||
- `elastic.out(1, 0.3)` — bouncy, use sparingly
|
||||
- `none` — scrubbed scroll tweens
|
||||
- `steps(n)` — sprite/stepped motion
|
||||
- Custom cubic-bezier equivalent: `CustomEase.create("x", "M0,0 C0.2,0 0,1 1,1")` (CustomEase is free)
|
||||
|
||||
## Performance and cleanup
|
||||
|
||||
- Animate `transform` (`x/y/xPercent/scale/rotation`) and `opacity` only — they are GPU-composited and skip layout/paint. Avoid animating `top/left/width/height`.
|
||||
- Set `will-change: transform` on heavy/pinned elements; remove after.
|
||||
- Batch many similar scroll reveals with `ScrollTrigger.batch()` instead of one trigger per element.
|
||||
- After a viewport/content change, call `ScrollTrigger.refresh()`.
|
||||
|
||||
SPA / framework cleanup is mandatory — orphaned triggers cause memory leaks and ghost pinning. Use `gsap.context()` (or `useGSAP` from `@gsap/react`):
|
||||
|
||||
```js
|
||||
useEffect(() => {
|
||||
const ctx = gsap.context(() => {
|
||||
// all gsap + ScrollTrigger code here
|
||||
}, rootRef);
|
||||
return () => ctx.revert(); // kills tweens, triggers, and reverts inline styles
|
||||
}, []);
|
||||
```
|
||||
|
||||
## Deliver & verify (standalone HTML)
|
||||
|
||||
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
|
||||
|
||||
For a self-contained animation (hero, reveal, loop, micro-scene) the deliverable is **one HTML file that opens directly in a browser** — no build step, no framework, no render pipeline. Match the deliverable to the weight of the work: a single file is the right tier for web motion; don't reach for a bundler when one file does the job.
|
||||
|
||||
**Output contract:**
|
||||
- One `.html` file: GSAP + plugins from CDN, your markup, and the animation in one inline `<script>`.
|
||||
- All motion on **one master timeline** (`const tl = gsap.timeline()`) — a single playhead you can seek.
|
||||
- Include the seek harness below so any moment can be frozen for inspection.
|
||||
|
||||
**Seek harness — freeze an exact moment for screenshots.** The web parallel of a video player's frame-pin: `?t=N` seeks the master timeline to `N` seconds and pauses, so a screenshot lands on a still, deterministic frame.
|
||||
|
||||
```html
|
||||
<script>
|
||||
// ... build your master timeline as `tl` ...
|
||||
const t = new URLSearchParams(location.search).get("t");
|
||||
if (t !== null) { tl.pause(); tl.seek(parseFloat(t)); } // frozen at t seconds
|
||||
// no ?t → plays normally
|
||||
window.__ready = true; // ready signal for headless wait
|
||||
console.log("duration", tl.duration());
|
||||
</script>
|
||||
```
|
||||
|
||||
**Verify loop — render → freeze → screenshot → check:**
|
||||
1. Open the file at three moments across the timeline — start, mid, end:
|
||||
`…/anim.html?t=0`, `?t=<dur/2>`, `?t=<dur>`. Read `tl.duration()` from the console for the end time.
|
||||
2. Screenshot each frozen frame.
|
||||
3. Check both **fidelity** (does it match the brief?) and **artifacts** (clipped text, elements off-canvas, FOUC before fonts load, jank at seams). Output should look intentional and finished.
|
||||
|
||||
Any headless screenshot tool works — your agent's browser tool, or Playwright:
|
||||
|
||||
```bash
|
||||
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/anim.html?t=1.2" frame-mid.png
|
||||
```
|
||||
|
||||
**Before you finish:**
|
||||
1. Opens standalone in a browser — no console errors, no missing CDN.
|
||||
2. All animation on one master timeline; `?t=N` freezes correctly.
|
||||
3. Screenshotted at start / mid / end — matches the brief, no artifacts.
|
||||
4. `prefers-reduced-motion` honored (timeline simplified or skipped).
|
||||
5. Easing is intentional — no accidental `linear` on spatial motion.
|
||||
|
||||
A complete runnable template with the harness wired in is in `examples/standalone-template.html`.
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Goal | API |
|
||||
|------|-----|
|
||||
| Sequence with overlap | `tl.from(...).from(..., "-=0.3")` |
|
||||
| Pin while scrolling | `scrollTrigger:{ pin:true, end:"+=N" }` |
|
||||
| Scrub to scroll | `scrollTrigger:{ scrub:1, ease:"none" }` |
|
||||
| Reveal lines of text | `SplitText.create(el,{type:"lines"})` |
|
||||
| Animate layout change | `Flip.getState` → mutate → `Flip.from` |
|
||||
| Fast pointer follow | `gsap.quickTo(el,"x",{...})` |
|
||||
| Kill everything | `ScrollTrigger.getAll().forEach(t=>t.kill())` |
|
||||
|
||||
## Reference files
|
||||
|
||||
- `references/scrolltrigger-cookbook.md` — pin, scrub, horizontal scroll, snap, `ScrollTrigger.batch()` reveals, parallax, nested triggers, and SPA cleanup patterns with full code.
|
||||
- `references/scrolltrigger-lenis.md` — full ScrollTrigger + Lenis/Locomotive smooth-scroll sync: canonical wiring, `scrollerProxy`, anchor links, reduced-motion, React (`useGSAP`/`useEffect`), debugging checklist, and symptom→cause table.
|
||||
- `examples/hero-timeline.js` — a complete, runnable hero entrance timeline with SplitText, staggered reveals, and reduced-motion handling.
|
||||
- `examples/standalone-template.html` — the deliverable template: self-contained (CDN GSAP), one master timeline, the `?t=N` seek harness for screenshot verification, and reduced-motion handling.
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* hero-timeline.js — complete, runnable GSAP hero entrance.
|
||||
*
|
||||
* Markup expected:
|
||||
* <section class="hero">
|
||||
* <p class="hero__eyebrow">EYEBROW</p>
|
||||
* <h1 class="hero__title">Big bold headline that wraps</h1>
|
||||
* <p class="hero__sub">Supporting copy.</p>
|
||||
* <div class="hero__actions"><a class="btn">Primary</a><a class="btn btn--ghost">Secondary</a></div>
|
||||
* <img class="hero__art" src="art.svg" alt="" />
|
||||
* </section>
|
||||
*
|
||||
* CSS prerequisite: each split line wrapper needs overflow:hidden for the mask reveal:
|
||||
* .hero__title .line { overflow: hidden; }
|
||||
*
|
||||
* Install: npm i gsap @gsap/react
|
||||
*/
|
||||
|
||||
import gsap from "gsap";
|
||||
import { SplitText } from "gsap/SplitText";
|
||||
|
||||
gsap.registerPlugin(SplitText);
|
||||
|
||||
export function playHeroIntro(root = document) {
|
||||
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
const q = gsap.utils.selector(root);
|
||||
|
||||
// Reduced motion: reveal everything instantly, no animation.
|
||||
if (reduceMotion) {
|
||||
gsap.set(q(".hero__eyebrow, .hero__sub, .hero__actions, .hero__art"), { autoAlpha: 1 });
|
||||
gsap.set(q(".hero__title"), { autoAlpha: 1 });
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
// Wait for fonts so SplitText computes correct line breaks.
|
||||
return document.fonts.ready.then(() => {
|
||||
const titleEl = q(".hero__title")[0];
|
||||
const split = new SplitText(titleEl, {
|
||||
type: "lines",
|
||||
linesClass: "line",
|
||||
autoSplit: true, // GSAP 3.13+: re-split on resize/font swap
|
||||
});
|
||||
|
||||
// Hidden start state (prevents flash of unstyled content).
|
||||
gsap.set(q(".hero__eyebrow, .hero__sub, .hero__actions, .hero__art"), { autoAlpha: 0 });
|
||||
gsap.set(titleEl, { autoAlpha: 1 });
|
||||
|
||||
const tl = gsap.timeline({
|
||||
defaults: { ease: "power3.out", duration: 0.8 },
|
||||
onComplete: () => split.revert(), // restore clean DOM once done (optional)
|
||||
});
|
||||
|
||||
tl.from(".hero__eyebrow", { y: 16, autoAlpha: 0, duration: 0.5 })
|
||||
.from(split.lines, { yPercent: 110, stagger: 0.12, duration: 0.9, ease: "power4.out" }, "-=0.2")
|
||||
.from(".hero__sub", { y: 20, autoAlpha: 0 }, "-=0.6")
|
||||
.from(".hero__actions .btn", { y: 12, autoAlpha: 0, stagger: 0.1, duration: 0.5 }, "-=0.4")
|
||||
.from(".hero__art", { scale: 0.92, autoAlpha: 0, ease: "back.out(1.4)", duration: 1.1 }, "<0.1");
|
||||
|
||||
return tl;
|
||||
});
|
||||
}
|
||||
|
||||
// Auto-run on DOM ready when imported directly in a page.
|
||||
if (typeof window !== "undefined" && document.querySelector(".hero")) {
|
||||
if (document.readyState !== "loading") playHeroIntro();
|
||||
else document.addEventListener("DOMContentLoaded", () => playHeroIntro());
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>loading</title>
|
||||
<!-- GSAP core from CDN — no build step. Add plugins the same way if needed:
|
||||
https://cdnjs.cloudflare.com/ajax/libs/gsap/3.13.0/ScrollTrigger.min.js -->
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.13.0/gsap.min.js"></script>
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
* { margin: 0; box-sizing: border-box; }
|
||||
body {
|
||||
min-height: 100svh; display: grid; place-items: center;
|
||||
background: radial-gradient(120% 120% at 50% 0%, #1b1f3b 0%, #0a0a12 60%);
|
||||
font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
|
||||
color: #f4f5ff; overflow: hidden;
|
||||
}
|
||||
.stage { text-align: center; padding: 6vmin; }
|
||||
.title { font-size: clamp(2.5rem, 9vw, 6rem); font-weight: 800; letter-spacing: -0.03em; line-height: 1; }
|
||||
.sub { font-size: clamp(1rem, 3.2vw, 1.6rem); margin-top: 1.2rem; color: #aab; }
|
||||
.cta { display: inline-block; margin-top: 2.4rem; padding: 0.9rem 1.8rem;
|
||||
border-radius: 999px; background: #5b6cff; color: #fff; font-weight: 600; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="stage">
|
||||
<h1 class="title">Ship it.</h1>
|
||||
<p class="sub">A standalone, screenshot-verifiable GSAP scene.</p>
|
||||
<a class="cta" href="#">Get started</a>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
|
||||
// ── One master timeline: a single playhead the harness can seek ──────────
|
||||
const tl = gsap.timeline({ defaults: { ease: "power3.out", duration: 0.7 } });
|
||||
|
||||
if (reduce) {
|
||||
// Reduced motion: no spatial movement — just make the final state visible.
|
||||
gsap.set([".title", ".sub", ".cta"], { opacity: 1, y: 0 });
|
||||
} else {
|
||||
tl.from(".title", { yPercent: 110, opacity: 0, ease: "power4.out", duration: 0.9 })
|
||||
.from(".sub", { y: 24, opacity: 0 }, "-=0.45")
|
||||
.from(".cta", { scale: 0.9, opacity: 0, ease: "back.out(1.7)" }, "-=0.3");
|
||||
}
|
||||
|
||||
// ── Seek harness: ?t=N freezes the timeline at N seconds for a clean shot ─
|
||||
const t = new URLSearchParams(location.search).get("t");
|
||||
if (t !== null) { tl.pause(); tl.seek(parseFloat(t)); } // deterministic frozen frame
|
||||
// no ?t → plays normally on load
|
||||
|
||||
// ── Ready signals for headless verification ──────────────────────────────
|
||||
window.__ready = true;
|
||||
document.title = "ready";
|
||||
console.log("duration", tl.duration()); // end time for the ?t=<dur> shot
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,181 @@
|
||||
# ScrollTrigger Cookbook
|
||||
|
||||
Runnable patterns for GSAP 3.12+. Register first:
|
||||
|
||||
```js
|
||||
import gsap from "gsap";
|
||||
import { ScrollTrigger } from "gsap/ScrollTrigger";
|
||||
gsap.registerPlugin(ScrollTrigger);
|
||||
```
|
||||
|
||||
## 1. Pin a section and scrub a timeline through it
|
||||
|
||||
The most common scrollytelling pattern: hold a section fixed and drive a multi-step timeline with scroll.
|
||||
|
||||
```js
|
||||
const tl = gsap.timeline({
|
||||
scrollTrigger: {
|
||||
trigger: ".story",
|
||||
start: "top top",
|
||||
end: "+=3000", // total scroll distance the pin lasts
|
||||
pin: true,
|
||||
scrub: 1,
|
||||
anticipatePin: 1, // reduces a 1-frame jump when pinning fast scroll
|
||||
},
|
||||
});
|
||||
|
||||
tl.from(".story .step-1", { autoAlpha: 0, y: 60 })
|
||||
.from(".story .step-2", { autoAlpha: 0, y: 60 })
|
||||
.to(".story .bg", { scale: 1.2, ease: "none" }, 0); // runs across whole timeline
|
||||
```
|
||||
|
||||
Tips:
|
||||
- Each tween occupies an equal slice of the pinned distance unless you set durations/positions.
|
||||
- `pinSpacing: true` (default) adds padding so content below does not jump. Set `false` only when overlaying.
|
||||
- If the pinned element is inside a transformed/`overflow` ancestor, pinning breaks — pin a top-level element or set `pinReparent: true`.
|
||||
|
||||
## 2. Horizontal scroll (panels move sideways as the page scrolls vertically)
|
||||
|
||||
```html
|
||||
<section class="h-wrap"><div class="track">
|
||||
<div class="panel">1</div><div class="panel">2</div><div class="panel">3</div>
|
||||
</div></section>
|
||||
```
|
||||
|
||||
```css
|
||||
.track { display: flex; width: max-content; }
|
||||
.panel { width: 100vw; height: 100vh; flex: 0 0 100vw; }
|
||||
```
|
||||
|
||||
```js
|
||||
const track = document.querySelector(".track");
|
||||
gsap.to(track, {
|
||||
x: () => -(track.scrollWidth - window.innerWidth), // function = recalculated on refresh
|
||||
ease: "none",
|
||||
scrollTrigger: {
|
||||
trigger: ".h-wrap",
|
||||
pin: true,
|
||||
scrub: 1,
|
||||
end: () => "+=" + (track.scrollWidth - window.innerWidth),
|
||||
invalidateOnRefresh: true, // re-run the x function on resize
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
`invalidateOnRefresh: true` plus function-based values is the correct way to stay responsive.
|
||||
|
||||
## 3. Snap to sections
|
||||
|
||||
```js
|
||||
gsap.to(".sections", {
|
||||
scrollTrigger: {
|
||||
trigger: ".sections",
|
||||
pin: true,
|
||||
scrub: 1,
|
||||
end: "+=4000",
|
||||
snap: {
|
||||
snapTo: 1 / 4, // 5 evenly spaced points (labels also possible: "labels")
|
||||
duration: { min: 0.2, max: 0.6 },
|
||||
delay: 0.05,
|
||||
ease: "power1.inOut",
|
||||
},
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
To snap to timeline labels: build a labeled timeline and use `snap: "labelsDirectional"`.
|
||||
|
||||
## 4. Batch reveals (performant many-element fade-in)
|
||||
|
||||
Instead of creating one ScrollTrigger per card (expensive at scale), batch them:
|
||||
|
||||
```js
|
||||
ScrollTrigger.batch(".card", {
|
||||
start: "top 85%",
|
||||
onEnter: (els) =>
|
||||
gsap.from(els, { autoAlpha: 0, y: 40, stagger: 0.12, overwrite: true }),
|
||||
onLeaveBack: (els) =>
|
||||
gsap.to(els, { autoAlpha: 0, y: 40, stagger: 0.12, overwrite: true }),
|
||||
});
|
||||
```
|
||||
|
||||
Set the initial hidden state to avoid a flash before JS runs: `gsap.set(".card", { autoAlpha: 0 })`.
|
||||
|
||||
## 5. Parallax layers
|
||||
|
||||
```js
|
||||
gsap.utils.toArray(".parallax").forEach((layer) => {
|
||||
const depth = layer.dataset.depth || 0.3; // 0 = static, 1 = scrolls with page
|
||||
gsap.to(layer, {
|
||||
yPercent: -depth * 100,
|
||||
ease: "none",
|
||||
scrollTrigger: { trigger: layer.parentElement, scrub: true, start: "top bottom", end: "bottom top" },
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## 6. Linked timelines / containerAnimation (triggers inside horizontal scroll)
|
||||
|
||||
To trigger animations off elements that move horizontally inside a pinned horizontal scroller, pass the horizontal tween as `containerAnimation`:
|
||||
|
||||
```js
|
||||
const scrollTween = gsap.to(track, { x: -2000, ease: "none",
|
||||
scrollTrigger: { trigger: ".h-wrap", pin: true, scrub: 1, end: "+=2000" } });
|
||||
|
||||
gsap.from(".panel-2 .title", {
|
||||
autoAlpha: 0, y: 50,
|
||||
scrollTrigger: { trigger: ".panel-2 .title", containerAnimation: scrollTween, start: "left center" },
|
||||
});
|
||||
```
|
||||
|
||||
Note `start: "left center"` uses horizontal keywords because the trigger moves horizontally.
|
||||
|
||||
## 7. Refresh on dynamic content
|
||||
|
||||
Images and lazy content change layout after triggers are computed. Refresh when ready:
|
||||
|
||||
```js
|
||||
window.addEventListener("load", () => ScrollTrigger.refresh());
|
||||
imagesLoaded(document.body, () => ScrollTrigger.refresh()); // if using imagesLoaded lib
|
||||
```
|
||||
|
||||
For accordions/tabs that change height, call `ScrollTrigger.refresh()` after the layout settles.
|
||||
|
||||
## 8. SPA / React cleanup (critical)
|
||||
|
||||
Orphaned ScrollTriggers cause ghost pins, leaks, and stacking bugs on route changes. Always scope and revert.
|
||||
|
||||
React with `@gsap/react`:
|
||||
|
||||
```jsx
|
||||
import { useGSAP } from "@gsap/react";
|
||||
|
||||
function Section() {
|
||||
const root = useRef(null);
|
||||
useGSAP(() => {
|
||||
gsap.from(".item", {
|
||||
autoAlpha: 0, y: 40, stagger: 0.1,
|
||||
scrollTrigger: { trigger: ".item", start: "top 80%" },
|
||||
});
|
||||
}, { scope: root }); // auto-reverts on unmount
|
||||
return <div ref={root}>...</div>;
|
||||
}
|
||||
```
|
||||
|
||||
Plain SPA / manual:
|
||||
|
||||
```js
|
||||
const ctx = gsap.context(() => { /* all gsap code */ }, rootEl);
|
||||
// on teardown / route leave:
|
||||
ctx.revert();
|
||||
```
|
||||
|
||||
Nuclear option (e.g. global router hook): `ScrollTrigger.getAll().forEach((t) => t.kill());`
|
||||
|
||||
## Debugging checklist
|
||||
|
||||
- Triggers fire at wrong scroll position → likely created before images loaded; call `ScrollTrigger.refresh()`.
|
||||
- Pinned element jumps to top-left → it has a transformed/`will-change`/`overflow:hidden` ancestor; pin higher up.
|
||||
- Animation plays once then never resets → set appropriate `toggleActions` or use `scrub`.
|
||||
- Horizontal scroll not responsive → use function-based `x`/`end` + `invalidateOnRefresh: true`.
|
||||
- Markers misaligned → leftover triggers from previous render; ensure cleanup runs.
|
||||
@@ -0,0 +1,255 @@
|
||||
# ScrollTrigger + Lenis / Locomotive smooth-scroll sync
|
||||
|
||||
Wire GSAP ScrollTrigger together with Lenis (or Locomotive) smooth scrolling so there is no jitter, no marker drift, no broken pins, and no flipped/laggy scroll direction. Every one of those bugs has the same root cause: two animation loops running independently. Lenis transforms the scroll position on its own `requestAnimationFrame` loop while ScrollTrigger reads scroll on GSAP's ticker — when they tick separately, ScrollTrigger samples a stale position and everything desyncs. The fix is to run one loop: let GSAP's ticker drive Lenis, and tell ScrollTrigger to update on every Lenis scroll.
|
||||
|
||||
## The one canonical wiring (Lenis)
|
||||
|
||||
This is the entire correct setup. Do not add a separate `requestAnimationFrame` loop for Lenis — that is the most common mistake and the source of nearly all desync.
|
||||
|
||||
```js
|
||||
import Lenis from 'lenis';
|
||||
import gsap from 'gsap';
|
||||
import { ScrollTrigger } from 'gsap/ScrollTrigger';
|
||||
|
||||
gsap.registerPlugin(ScrollTrigger);
|
||||
|
||||
const lenis = new Lenis({
|
||||
duration: 1.2,
|
||||
smoothWheel: true,
|
||||
// do NOT enable Lenis's own rAF; GSAP's ticker drives it (below)
|
||||
});
|
||||
|
||||
// 1. Update ScrollTrigger every time Lenis scrolls
|
||||
lenis.on('scroll', ScrollTrigger.update);
|
||||
|
||||
// 2. Drive Lenis from GSAP's ticker (single shared loop).
|
||||
// gsap.ticker time is in SECONDS; Lenis expects MILLISECONDS.
|
||||
gsap.ticker.add((time) => {
|
||||
lenis.raf(time * 1000);
|
||||
});
|
||||
|
||||
// 3. Disable GSAP's lag smoothing so ScrollTrigger never defers/
|
||||
// catches up against Lenis (prevents jitter on heavy frames)
|
||||
gsap.ticker.lagSmoothing(0);
|
||||
```
|
||||
|
||||
Three lines do all the work:
|
||||
|
||||
1. `lenis.on('scroll', ScrollTrigger.update)` — ScrollTrigger recomputes positions the instant Lenis moves the page, so triggers/markers/pins track the smoothed scroll exactly.
|
||||
2. `gsap.ticker.add(time => lenis.raf(time * 1000))` — Lenis advances inside GSAP's loop, guaranteeing both run on the same frame and in the same order. Critical unit conversion: `gsap.ticker` passes seconds, `lenis.raf()` wants milliseconds, so multiply by 1000.
|
||||
3. `gsap.ticker.lagSmoothing(0)` — disables GSAP's catch-up behavior that, combined with Lenis, causes visible jitter when a frame is slow.
|
||||
|
||||
After this, never call `requestAnimationFrame(raf)` for Lenis yourself. If any tutorial code has a standalone `function raf(time){ lenis.raf(time); requestAnimationFrame(raf) }` loop, delete it — it competes with the ticker and reintroduces jitter and direction lag.
|
||||
|
||||
## Locomotive Scroll variant
|
||||
|
||||
Locomotive needs `scrollerProxy` because it scrolls an inner element, not `window`. The principle is identical (one loop, update ScrollTrigger on scroll), but the proxy maps coordinates:
|
||||
|
||||
```js
|
||||
const locoScroll = new LocomotiveScroll({
|
||||
el: document.querySelector('[data-scroll-container]'),
|
||||
smooth: true,
|
||||
});
|
||||
|
||||
locoScroll.on('scroll', ScrollTrigger.update);
|
||||
|
||||
ScrollTrigger.scrollerProxy('[data-scroll-container]', {
|
||||
scrollTop(value) {
|
||||
return arguments.length
|
||||
? locoScroll.scrollTo(value, { duration: 0, disableLerp: true })
|
||||
: locoScroll.scroll.instance.scroll.y;
|
||||
},
|
||||
getBoundingClientRect() {
|
||||
return { top: 0, left: 0, width: innerWidth, height: innerHeight };
|
||||
},
|
||||
pinType: document.querySelector('[data-scroll-container]').style.transform
|
||||
? 'transform' : 'fixed',
|
||||
});
|
||||
|
||||
ScrollTrigger.addEventListener('refresh', () => locoScroll.update());
|
||||
ScrollTrigger.refresh();
|
||||
```
|
||||
|
||||
Every ScrollTrigger then needs `scroller: '[data-scroll-container]'`. Lenis is simpler because it scrolls the real document, so no `scrollerProxy` is needed.
|
||||
|
||||
## Pins, refresh, and resize
|
||||
|
||||
- Pinned ScrollTriggers work without `scrollerProxy` under Lenis because Lenis scrolls the document body. If pins still jump, ensure no rogue rAF loop exists and that `ScrollTrigger.update` is wired.
|
||||
- On dynamic content/resize, call `ScrollTrigger.refresh()` after layout settles. With Lenis, also call `lenis.resize()` if container size changes.
|
||||
- For elements that should *not* be smoothed (e.g. a modal that scrolls natively), mark with `data-lenis-prevent` so Lenis ignores them.
|
||||
|
||||
## Anchor links with smooth scroll
|
||||
|
||||
Native `<a href="#section">` jumps bypass Lenis (instant jump, then Lenis fights it). Route anchors through `lenis.scrollTo`:
|
||||
|
||||
```js
|
||||
document.querySelectorAll('a[href^="#"]').forEach((a) => {
|
||||
a.addEventListener('click', (e) => {
|
||||
const id = a.getAttribute('href');
|
||||
if (id.length > 1) {
|
||||
e.preventDefault();
|
||||
lenis.scrollTo(id, { offset: 0 }); // accepts selector, element, or number
|
||||
}
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
If a sticky header overlaps the target, pass a negative offset or an offset callback:
|
||||
|
||||
```js
|
||||
lenis.scrollTo(targetEl, { offset: -80 }); // 80px sticky header
|
||||
```
|
||||
|
||||
## Reduced-motion gate
|
||||
|
||||
Respect `prefers-reduced-motion`: skip smooth scrolling entirely (do not instantiate Lenis, or stop it) and let ScrollTrigger run on native scroll.
|
||||
|
||||
```js
|
||||
const prefersReduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
let lenis;
|
||||
if (!prefersReduced) {
|
||||
lenis = new Lenis({ duration: 1.2 });
|
||||
lenis.on('scroll', ScrollTrigger.update);
|
||||
gsap.ticker.add((time) => lenis.raf(time * 1000));
|
||||
gsap.ticker.lagSmoothing(0);
|
||||
}
|
||||
// ScrollTrigger animations are defined normally and work with or without Lenis
|
||||
```
|
||||
|
||||
## Cleanup (SPA / React / route changes)
|
||||
|
||||
Destroy Lenis and remove the ticker callback on unmount, or stacked loops accumulate:
|
||||
|
||||
```js
|
||||
function setup() {
|
||||
const update = (time) => lenis.raf(time * 1000);
|
||||
lenis.on('scroll', ScrollTrigger.update);
|
||||
gsap.ticker.add(update);
|
||||
gsap.ticker.lagSmoothing(0);
|
||||
return () => {
|
||||
gsap.ticker.remove(update);
|
||||
lenis.destroy();
|
||||
ScrollTrigger.getAll().forEach((t) => t.kill());
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## Debugging checklist (work top to bottom)
|
||||
|
||||
1. **Is there a rogue rAF loop?** Search the codebase for `requestAnimationFrame` near `lenis.raf`. If Lenis is also driven by `gsap.ticker`, delete the standalone loop. Two loops = jitter, lag, flipped feel.
|
||||
2. **Unit conversion present?** Confirm `lenis.raf(time * 1000)` inside the ticker. Missing `* 1000` makes scroll feel stuck or wildly slow.
|
||||
3. **Is `ScrollTrigger.update` subscribed?** `lenis.on('scroll', ScrollTrigger.update)` must exist. Without it, markers and triggers drift behind the smoothed position.
|
||||
4. **Is `lagSmoothing(0)` set?** Without it, heavy frames cause GSAP to "catch up", visible as jitter.
|
||||
5. **Markers on for diagnosis.** Add `markers: true` to a trigger. If markers sit at the *native* scroll position but content moves with smoothed scroll, the update subscription is missing or a proxy is mis-set.
|
||||
6. **Pins jumping?** Confirm no proxy is set for Lenis (it scrolls the document). For Locomotive, confirm `pinType` and `scroller` are correct.
|
||||
7. **After dynamic content / fonts / images load**, call `ScrollTrigger.refresh()`. Stale measurements cause triggers to fire at wrong offsets.
|
||||
8. **Nested scroll areas** (modals, code blocks) misbehave? Add `data-lenis-prevent` to the scrollable child.
|
||||
9. **Cleanup on route change?** In SPAs, verify `gsap.ticker.remove(update)`, `lenis.destroy()`, and killing ScrollTriggers — otherwise each navigation stacks another loop.
|
||||
|
||||
## Symptom → cause table
|
||||
|
||||
| Symptom | Most likely cause |
|
||||
|---|---|
|
||||
| General jitter/stutter | Standalone rAF loop + ticker both driving Lenis |
|
||||
| Scroll stuck / barely moves | Missing `* 1000` unit conversion |
|
||||
| Markers offset from triggers | `ScrollTrigger.update` not bound to `lenis.on('scroll')` |
|
||||
| Jitter only on heavy frames | `lagSmoothing(0)` not set |
|
||||
| Pins jump / break | Proxy wrongly set under Lenis, or wrong `pinType` (Loco) |
|
||||
| Animations a frame behind | Two loops out of order; consolidate to one ticker |
|
||||
| Anchor links jump then snap back | Native `#hash` jump not routed via `lenis.scrollTo` |
|
||||
| Triggers fire at wrong scroll position | Missing `ScrollTrigger.refresh()` after content/layout change |
|
||||
| Worse after each route change | No cleanup; loops/triggers accumulating |
|
||||
| Inner scroll container won't scroll | Lenis intercepting; add `data-lenis-prevent` |
|
||||
|
||||
## Complete React integration (useGSAP)
|
||||
|
||||
```jsx
|
||||
'use client';
|
||||
import { useRef } from 'react';
|
||||
import Lenis from 'lenis';
|
||||
import gsap from 'gsap';
|
||||
import { ScrollTrigger } from 'gsap/ScrollTrigger';
|
||||
import { useGSAP } from '@gsap/react';
|
||||
|
||||
gsap.registerPlugin(ScrollTrigger, useGSAP);
|
||||
|
||||
export default function ScrollSection() {
|
||||
const root = useRef(null);
|
||||
|
||||
useGSAP(() => {
|
||||
const prefersReduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
let lenis;
|
||||
let update;
|
||||
if (!prefersReduced) {
|
||||
lenis = new Lenis({ duration: 1.2, smoothWheel: true });
|
||||
lenis.on('scroll', ScrollTrigger.update);
|
||||
update = (time) => lenis.raf(time * 1000);
|
||||
gsap.ticker.add(update);
|
||||
gsap.ticker.lagSmoothing(0);
|
||||
}
|
||||
|
||||
gsap.to('.panel', {
|
||||
xPercent: -100,
|
||||
ease: 'none',
|
||||
scrollTrigger: {
|
||||
trigger: '.panel',
|
||||
start: 'top top',
|
||||
end: '+=1500',
|
||||
scrub: true,
|
||||
pin: true,
|
||||
// markers: true, // enable while debugging
|
||||
},
|
||||
});
|
||||
|
||||
return () => {
|
||||
if (lenis) {
|
||||
gsap.ticker.remove(update);
|
||||
lenis.destroy();
|
||||
}
|
||||
};
|
||||
}, { scope: root });
|
||||
|
||||
return (
|
||||
<div ref={root}>
|
||||
<section className="panel">…</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
`useGSAP` auto-reverts GSAP tweens/ScrollTriggers created in its scope on unmount; the returned function additionally tears down Lenis and the ticker callback so nothing leaks across navigations.
|
||||
|
||||
## Plain useEffect equivalent
|
||||
|
||||
```jsx
|
||||
useEffect(() => {
|
||||
const lenis = new Lenis({ duration: 1.2 });
|
||||
lenis.on('scroll', ScrollTrigger.update);
|
||||
const update = (t) => lenis.raf(t * 1000);
|
||||
gsap.ticker.add(update);
|
||||
gsap.ticker.lagSmoothing(0);
|
||||
|
||||
const ctx = gsap.context(() => {
|
||||
// ...ScrollTrigger animations here...
|
||||
});
|
||||
|
||||
return () => {
|
||||
gsap.ticker.remove(update);
|
||||
lenis.destroy();
|
||||
ctx.revert();
|
||||
};
|
||||
}, []);
|
||||
```
|
||||
|
||||
## Excluding regions from smooth scroll
|
||||
|
||||
```html
|
||||
<div class="code-block" data-lenis-prevent>…natively scrollable…</div>
|
||||
```
|
||||
|
||||
`data-lenis-prevent` on a scrollable element makes Lenis ignore wheel/touch there, so inner scrolling works normally while the page stays smooth.
|
||||
|
||||
---
|
||||
Sync ScrollTrigger to smooth scroll and the timeline tracks the page perfectly. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=gsap-web)** — the AI motion agent for editable, on-brand motion graphics.
|
||||
Whitespace-only changes.
@@ -0,0 +1,180 @@
|
||||
---
|
||||
name: lottie-animation
|
||||
description: This skill should be used when the user asks to "add a Lottie animation", "play a .lottie or .json animation", "integrate a Bodymovin/After Effects animation on web or mobile", "control Lottie playback / segments", "make a scroll-driven Lottie", "recolor a Lottie at runtime", or "export an AE animation to Lottie". Covers dotLottie/lottie-web integration, playback control, interactivity, theming, and the AE export checklist.
|
||||
version: 0.1.0
|
||||
---
|
||||
|
||||
# Lottie Animation
|
||||
|
||||
The bridge from After Effects to product: vector animation shipped as JSON (or zipped `.lottie`), tiny and resolution-independent, played by a runtime on web, iOS, Android, and React Native. This skill covers integrating, controlling, and exporting Lottie.
|
||||
|
||||
## When to use
|
||||
|
||||
- Ship a designer's AE animation to web/iOS/Android/React Native
|
||||
- Looping illustrations, onboarding, empty states, animated icons
|
||||
- Scroll-driven or interaction-driven vector playback (hover, click, cursor)
|
||||
- Runtime theming/recoloring instead of re-exporting per brand
|
||||
|
||||
## Formats: .json vs .lottie
|
||||
|
||||
- `.json` — the raw Bodymovin output. Human-readable, larger.
|
||||
- `.lottie` — a zipped container (often 60–80% smaller) that can bundle multiple animations, images, and theming. Preferred for shipping. Player: `@lottiefiles/dotlottie-web` (modern, canvas + WASM) supersedes the older `lottie-web`.
|
||||
|
||||
Prefer the **dotLottie** runtime for new work; use `lottie-web` only for legacy `.json` + SVG renderer needs.
|
||||
|
||||
## Core workflow (web, dotLottie)
|
||||
|
||||
```bash
|
||||
npm i @lottiefiles/dotlottie-web # vanilla
|
||||
npm i @lottiefiles/dotlottie-react # React wrapper
|
||||
```
|
||||
|
||||
Vanilla:
|
||||
|
||||
```js
|
||||
import { DotLottie } from "@lottiefiles/dotlottie-web";
|
||||
|
||||
const dotLottie = new DotLottie({
|
||||
canvas: document.querySelector("#lottie"), // a <canvas> element
|
||||
src: "/hero.lottie", // or .json
|
||||
loop: true,
|
||||
autoplay: true,
|
||||
// speed: 1, mode: "forward" | "reverse" | "bounce", renderConfig: { autoResize: true }
|
||||
});
|
||||
```
|
||||
|
||||
React:
|
||||
|
||||
```jsx
|
||||
import { DotLottieReact } from "@lottiefiles/dotlottie-react";
|
||||
|
||||
function Hero() {
|
||||
return <DotLottieReact src="/hero.lottie" loop autoplay style={{ width: 320 }} />;
|
||||
}
|
||||
```
|
||||
|
||||
Capture the instance to control it:
|
||||
|
||||
```jsx
|
||||
const [dl, setDl] = useState(null);
|
||||
<DotLottieReact src="/icon.lottie" dotLottieRefCallback={setDl} />;
|
||||
// dl?.play(); dl?.pause(); dl?.setSpeed(2);
|
||||
```
|
||||
|
||||
## Playback control
|
||||
|
||||
```js
|
||||
dotLottie.play();
|
||||
dotLottie.pause();
|
||||
dotLottie.stop();
|
||||
dotLottie.setSpeed(1.5);
|
||||
dotLottie.setMode("bounce"); // forward | reverse | bounce | reverse-bounce
|
||||
dotLottie.setFrame(42); // jump to a frame
|
||||
dotLottie.setSegment(30, 90); // constrain playback to a frame range (e.g. a "loading" loop)
|
||||
```
|
||||
|
||||
Events drive sequencing and UI:
|
||||
|
||||
```js
|
||||
dotLottie.addEventListener("load", () => { /* totalFrames now available */ });
|
||||
dotLottie.addEventListener("complete", () => { /* non-looping playback finished */ });
|
||||
dotLottie.addEventListener("frame", ({ currentFrame }) => { /* per-frame */ });
|
||||
```
|
||||
|
||||
State-machine style (e.g. button that plays "checked" segment then idles): play a segment, listen for `complete`, then `setSegment` to the idle loop.
|
||||
|
||||
## Scroll-driven Lottie (no GSAP needed)
|
||||
|
||||
Map scroll progress (0–1) to a frame. Pause autoplay and drive frames yourself.
|
||||
|
||||
```js
|
||||
const dotLottie = new DotLottie({ canvas, src: "/scroll.lottie", autoplay: false });
|
||||
let total = 0;
|
||||
dotLottie.addEventListener("load", () => { total = dotLottie.totalFrames; });
|
||||
|
||||
window.addEventListener("scroll", () => {
|
||||
const el = canvas.closest(".scrolly");
|
||||
const rect = el.getBoundingClientRect();
|
||||
const p = clamp(-rect.top / (rect.height - window.innerHeight), 0, 1); // 0..1 through the section
|
||||
dotLottie.setFrame(p * (total - 1));
|
||||
}, { passive: true });
|
||||
|
||||
const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
|
||||
```
|
||||
|
||||
For richer interaction (hover-to-play, click toggles, cursor-follow) without writing the wiring, use `@lottiefiles/lottie-interactivity`, which maps `scroll`, `hover`, `click`, `play`, and `cursor` modes to frame ranges declaratively.
|
||||
|
||||
## Runtime theming / recoloring
|
||||
|
||||
Two paths:
|
||||
- **dotLottie themes**: a `.lottie` can embed named color themes; switch with `dotLottie.setTheme("dark")` / `loadTheme(...)`. Authored in LottieFiles tooling — no re-export to recolor.
|
||||
- **Manual color override**: load the JSON, walk `layers[].shapes[]` and patch `c.k` color arrays (normalized 0–1 RGBA), then init the player with the modified object. Brittle (depends on layer structure) — prefer themes or CSS-driven SVG-renderer (`lottie-web` `rendererSettings`) when you must restyle by class.
|
||||
|
||||
## Mobile runtimes (parity)
|
||||
|
||||
- iOS — `lottie-ios` (`LottieAnimationView`): `.play()`, `.currentProgress`, `.play(fromFrame:toFrame:)`.
|
||||
- Android — `lottie-android` (`LottieAnimationView` / Compose `LottieAnimation`): `setMinAndMaxFrame`, `progress`.
|
||||
- React Native — `lottie-react-native` (`<LottieView source={...} progress={anim} />`, drive `progress` with `Animated`).
|
||||
|
||||
The same `.lottie`/`.json` plays across all; segments and progress concepts match the web API.
|
||||
|
||||
## Optimization
|
||||
|
||||
- Ship `.lottie` (zipped) over raw `.json`; lazy-load offscreen players and pause when not visible (`IntersectionObserver` → `play`/`pause`).
|
||||
- Prefer the canvas/WASM dotLottie renderer for many simultaneous animations; SVG renderer (lottie-web) is fine for one crisp icon but costs more DOM for complex files.
|
||||
- Keep AE comps small: fewer layers/keyframes, no large embedded rasters; flatten precomps where possible. File size tracks keyframe and path complexity, not duration.
|
||||
- Recolor at runtime (themes) instead of exporting a file per brand/theme.
|
||||
|
||||
## Deliver & verify (standalone HTML)
|
||||
|
||||
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
|
||||
|
||||
For a self-contained Lottie demo (looping illustration, animated icon, empty state) the deliverable is **one HTML file that opens directly in a browser** — the dotLottie/lottie-web runtime from CDN, a `<canvas>`, and your `.lottie`/`.json` (a relative file or a data URL). No build step. One file is the right tier for shipping a player; don't reach for a bundler.
|
||||
|
||||
**Output contract:**
|
||||
- One `.html` file: the runtime via CDN (`@lottiefiles/dotlottie-web`), the canvas, and `autoplay:false` so the frame is yours to drive.
|
||||
- Include the seek harness so any frame can be frozen for a screenshot.
|
||||
|
||||
**Seek harness — freeze an exact frame.** `?t=N` jumps to a frame and holds it so a screenshot lands on a still, deterministic frame. Lottie's playhead is in frames, so stop on the frame directly:
|
||||
|
||||
```html
|
||||
<script>
|
||||
const dl = new DotLottie({ canvas, src: "/icon.lottie", autoplay: false });
|
||||
dl.addEventListener("load", () => {
|
||||
const t = new URLSearchParams(location.search).get("t");
|
||||
if (t !== null) dl.setFrame(parseFloat(t)); // freeze on frame N (lottie-web: anim.goToAndStop(N, true))
|
||||
else dl.play();
|
||||
console.log("totalFrames", dl.totalFrames); // read for end-frame
|
||||
window.__ready = true;
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
**Verify loop — render → freeze → screenshot → check:** open the file at first / mid / last frame (`?t=0`, `?t=<total/2>`, `?t=<total-1>`; read `totalFrames` from the console), screenshot each, and check **fidelity** (colors/theme correct, segment loops where intended) plus **artifacts** (canvas blurry from missing `autoResize`/DPR, clipped composition, FOUC before the file loads, jank). Any headless tool works:
|
||||
|
||||
```bash
|
||||
npx playwright screenshot --wait-for-timeout=600 "file://$PWD/lottie.html?t=42" frame-mid.png
|
||||
```
|
||||
|
||||
**Before you finish:**
|
||||
1. Opens standalone — no console errors, CDN runtime and the `.lottie`/`.json` load.
|
||||
2. `?t=N` (`setFrame`/`goToAndStop`) freezes the correct, deterministic frame.
|
||||
3. Screenshotted at first / mid / last frame — matches the brief, sharp, no clipping.
|
||||
4. `prefers-reduced-motion` honored — don't `autoplay` a loop; show a static frame or offer a play control.
|
||||
5. Easing is intentional — playback speed/segment chosen on purpose, motion baked in AE reads as designed.
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Goal | Call |
|
||||
|------|------|
|
||||
| Play a range | `setSegment(start, end)` |
|
||||
| Jump to frame | `setFrame(n)` |
|
||||
| Reverse / bounce | `setMode("reverse"|"bounce")` |
|
||||
| Scroll-drive | `autoplay:false` + `setFrame(p*totalFrames)` |
|
||||
| Theme swap | `setTheme("dark")` |
|
||||
| Know length | `totalFrames` after `load` event |
|
||||
| Declarative interactivity | `@lottiefiles/lottie-interactivity` |
|
||||
|
||||
## Reference files
|
||||
|
||||
- `references/integration-and-export.md` — full dotLottie-web + React setup and event/segment control, `lottie-interactivity` mode configs, scroll/cursor patterns, runtime theming details, and the complete After Effects → Bodymovin export checklist with the list of unsupported AE features and how to work around them.
|
||||
@@ -0,0 +1,233 @@
|
||||
# Lottie Integration & Export (detailed)
|
||||
|
||||
## 1. dotLottie-web full setup
|
||||
|
||||
```bash
|
||||
npm i @lottiefiles/dotlottie-web
|
||||
```
|
||||
|
||||
```js
|
||||
import { DotLottie } from "@lottiefiles/dotlottie-web";
|
||||
|
||||
const dotLottie = new DotLottie({
|
||||
canvas: document.querySelector("#lottie"),
|
||||
src: "/assets/onboarding.lottie", // .lottie or .json (URL or same-origin path)
|
||||
autoplay: true,
|
||||
loop: true,
|
||||
speed: 1,
|
||||
mode: "forward", // forward | reverse | bounce | reverse-bounce
|
||||
useFrameInterpolation: true, // smoother than the source frame rate
|
||||
renderConfig: {
|
||||
autoResize: true, // keep the canvas crisp on resize/DPR changes
|
||||
devicePixelRatio: window.devicePixelRatio,
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
The canvas MUST be a real `<canvas>` element. For responsiveness, size the canvas via CSS and keep `autoResize: true`; the runtime handles the backing store.
|
||||
|
||||
### Lifecycle and events
|
||||
|
||||
```js
|
||||
dotLottie.addEventListener("load", () => console.log(dotLottie.totalFrames, dotLottie.duration));
|
||||
dotLottie.addEventListener("loadError", (e) => console.error("bad src", e));
|
||||
dotLottie.addEventListener("play", () => {});
|
||||
dotLottie.addEventListener("pause", () => {});
|
||||
dotLottie.addEventListener("complete", () => {}); // fires when a non-looping play finishes
|
||||
dotLottie.addEventListener("loop", ({ loopCount }) => {});
|
||||
dotLottie.addEventListener("frame", ({ currentFrame }) => {});
|
||||
|
||||
// always clean up (SPA/unmount)
|
||||
dotLottie.destroy();
|
||||
```
|
||||
|
||||
`totalFrames`, `duration`, and segment data are only valid AFTER the `load` event — read them there, not synchronously after construction.
|
||||
|
||||
### Multi-animation .lottie files
|
||||
|
||||
A single `.lottie` can hold several animations:
|
||||
|
||||
```js
|
||||
dotLottie.addEventListener("load", () => {
|
||||
console.log(dotLottie.manifest.animations); // list of animation ids
|
||||
});
|
||||
dotLottie.loadAnimation("success"); // switch by id without re-fetching
|
||||
```
|
||||
|
||||
## 2. React wrapper
|
||||
|
||||
```bash
|
||||
npm i @lottiefiles/dotlottie-react
|
||||
```
|
||||
|
||||
```jsx
|
||||
import { DotLottieReact } from "@lottiefiles/dotlottie-react";
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
function PlayButton() {
|
||||
const [dl, setDl] = useState(null);
|
||||
const [playing, setPlaying] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (!dl) return;
|
||||
const onComplete = () => setPlaying(false);
|
||||
dl.addEventListener("complete", onComplete);
|
||||
return () => dl.removeEventListener("complete", onComplete);
|
||||
}, [dl]);
|
||||
|
||||
return (
|
||||
<DotLottieReact
|
||||
src="/play.lottie"
|
||||
autoplay
|
||||
loop={false}
|
||||
dotLottieRefCallback={setDl} // capture instance for imperative control
|
||||
onClick={() => (playing ? dl.pause() : dl.play(), setPlaying((p) => !p))}
|
||||
style={{ width: 200, height: 200 }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Props mirror the constructor: `src, autoplay, loop, speed, mode, useFrameInterpolation, renderConfig, themeId, segment`.
|
||||
|
||||
## 3. Segments and state machines
|
||||
|
||||
```js
|
||||
// Loop only the "loading" portion (frames 30–90), then jump to a success segment.
|
||||
dotLottie.setSegment(30, 90);
|
||||
dotLottie.setLoop(true);
|
||||
dotLottie.play();
|
||||
|
||||
function resolveSuccess() {
|
||||
dotLottie.setLoop(false);
|
||||
dotLottie.setSegment(91, 140); // success burst
|
||||
dotLottie.play();
|
||||
}
|
||||
```
|
||||
|
||||
Pattern for icon toggles (e.g. like button): keep distinct frame ranges for each state in one file, and `setSegment` + `play` per interaction; listen for `complete` to settle into an idle range.
|
||||
|
||||
dotLottie also supports embedded **state machines** (`.lottie` with a `state-machine` definition): `dotLottie.stateMachineLoad("sm_id"); dotLottie.stateMachineStart();` then fire inputs/events — useful for complex interactive icons authored in LottieFiles without writing JS state logic.
|
||||
|
||||
## 4. lottie-interactivity (declarative)
|
||||
|
||||
```bash
|
||||
npm i @lottiefiles/lottie-interactivity
|
||||
```
|
||||
|
||||
Works with a `lottie-web`/dotLottie player instance (commonly the `<dotlottie-player>` / `<lottie-player>` web component):
|
||||
|
||||
```html
|
||||
<dotlottie-player id="firstLottie" src="/scroll.lottie" style="width:300px"></dotlottie-player>
|
||||
<script>
|
||||
LottieInteractivity.create({
|
||||
player: "#firstLottie",
|
||||
mode: "scroll",
|
||||
actions: [
|
||||
{ visibility: [0, 0.3], type: "stop", frames: [0] },
|
||||
{ visibility: [0.3, 1.0], type: "seek", frames: [0, 120] }, // map scroll → frames 0..120
|
||||
],
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
Modes:
|
||||
- `scroll` — tie frames to scroll position / element visibility (the canonical scrolly use).
|
||||
- `cursor` — drive frames from cursor position over the element (hover scrub).
|
||||
- `hover` — play on hover, control `loop`/`reset` on leave.
|
||||
- `click` — advance to the next sync state on each click.
|
||||
- `chain` — sequence multiple animations.
|
||||
|
||||
Use `type: "seek"` to scrub frames, `type: "loop"` / `"play"` / `"stop"` for segment behaviors.
|
||||
|
||||
## 5. Manual scroll mapping (full control, no extra lib)
|
||||
|
||||
```js
|
||||
const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
|
||||
let total = 0;
|
||||
dotLottie.addEventListener("load", () => { total = dotLottie.totalFrames - 1; });
|
||||
|
||||
const section = document.querySelector(".scrolly");
|
||||
function update() {
|
||||
const r = section.getBoundingClientRect();
|
||||
const scrollable = r.height - window.innerHeight;
|
||||
const p = clamp(-r.top / scrollable, 0, 1);
|
||||
dotLottie.setFrame(p * total);
|
||||
}
|
||||
window.addEventListener("scroll", update, { passive: true });
|
||||
window.addEventListener("resize", update);
|
||||
```
|
||||
|
||||
Pause when offscreen to save CPU:
|
||||
|
||||
```js
|
||||
new IntersectionObserver(([e]) => e.isIntersecting ? dotLottie.unfreeze() : dotLottie.freeze())
|
||||
.observe(canvas);
|
||||
```
|
||||
|
||||
## 6. Runtime theming
|
||||
|
||||
### Embedded themes (recommended)
|
||||
|
||||
A `.lottie` authored with named color themes:
|
||||
|
||||
```js
|
||||
dotLottie.addEventListener("load", () => {
|
||||
console.log(dotLottie.manifest.themes); // available theme ids
|
||||
dotLottie.setTheme("dark"); // swap colors with no re-fetch / re-export
|
||||
});
|
||||
// or per slot:
|
||||
dotLottie.setThemeData({ /* theme JSON */ });
|
||||
```
|
||||
|
||||
### Manual color patching (last resort)
|
||||
|
||||
```js
|
||||
const json = await fetch("/icon.json").then((r) => r.json());
|
||||
// Lottie colors are normalized 0..1 [r,g,b,a] arrays at shapes[].it[].c.k
|
||||
function recolor(layers, hex) {
|
||||
const [r, g, b] = hexToRgb01(hex);
|
||||
for (const layer of layers) {
|
||||
for (const sh of layer.shapes ?? []) {
|
||||
for (const it of sh.it ?? []) {
|
||||
if (it.ty === "fl" || it.ty === "st") { it.c.k = [r, g, b, 1]; } // fill / stroke
|
||||
}
|
||||
}
|
||||
if (layer.layers) recolor(layer.layers, hex); // precomps
|
||||
}
|
||||
}
|
||||
recolor(json.layers, "#ff5500");
|
||||
new DotLottie({ canvas, data: JSON.stringify(json), autoplay: true });
|
||||
```
|
||||
|
||||
This depends on the exact layer/shape structure and breaks if the file changes — prefer embedded themes, or use the `lottie-web` SVG renderer and target paths with CSS where the markup is stable.
|
||||
|
||||
## 7. After Effects → Bodymovin export checklist
|
||||
|
||||
Plugin: **Bodymovin** (or LottieFiles plugin). `Window → Extensions → Bodymovin`. Select the comp, set destination, configure, Render.
|
||||
|
||||
Pre-export checklist:
|
||||
1. Comp set to a sensible size and frame rate (24/30/60); avoid huge resolutions — Lottie is vector, the canvas scales.
|
||||
2. Name layers/comps clearly — names survive into JSON and aid runtime theming/targeting.
|
||||
3. Convert text you want crisp/animated-by-path to shapes if it uses unsupported text features; otherwise enable "Glyphs"/"Fonts" in Bodymovin settings for live text.
|
||||
4. Trim the work area to exactly the frames you ship; trailing frames bloat the file.
|
||||
5. In Bodymovin settings: enable **Compress assets / .lottie** output for the zipped format; enable "Glyphs" if using text; toggle "Standalone"/"Demo" only as needed.
|
||||
6. Replace embedded raster images with vectors where possible; if rasters are required, they inflate `.json` (consider `.lottie` which bundles them).
|
||||
7. Test the exported file in the LottieFiles preview AND your target runtime before handoff — renderers differ.
|
||||
|
||||
### Unsupported / partially-supported AE features (avoid or rework)
|
||||
|
||||
- **Expressions** — not evaluated by runtimes. Bake expression-driven motion to keyframes (Bodymovin can pre-render some) or remove. Heavy-expression rigs are the #1 source of "looks wrong in product".
|
||||
- **Effects** — most AE effects (blurs, glows, distort, particle systems, CC effects) are NOT supported. Only a small set (e.g. some Gaussian blur, drop shadow, tint, fill via supported attributes) survive, and inconsistently across platforms. Recreate looks with shape layers, gradients, and mattes.
|
||||
- **3D layers / camera** — not supported; fake depth with 2D scaling/position.
|
||||
- **Time remapping / nested time stretch** — flaky; pre-compose and bake.
|
||||
- **Auto-Orient, certain merge-paths modes, some matte combinations** — test explicitly.
|
||||
- **Audio** — not part of Lottie.
|
||||
- **Adjustment layers, layer styles (bevel/emboss/inner shadow)** — largely unsupported; convert to shapes/gradients.
|
||||
- **Track mattes** — alpha/luma mattes generally work but increase cost; flatten when possible.
|
||||
- **Gradients on strokes / complex gradient feathering** — limited; verify.
|
||||
|
||||
Workarounds summary: bake expressions to keyframes, replace effects with native shape/gradient/matte equivalents, flatten precomps, drop rasters, and verify on every target runtime (web/iOS/Android render slightly differently). Keep layer/keyframe count low for performance and file size.
|
||||
|
||||
---
|
||||
Export clean from After Effects and the dotLottie plays light everywhere. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=lottie-animation)** — the AI motion agent for editable, on-brand motion graphics.
|
||||
Whitespace-only changes.
@@ -0,0 +1,173 @@
|
||||
---
|
||||
name: micro-interaction
|
||||
description: This skill should be used when the user asks to "add a hover/press effect", "animate a toggle or switch", "build an animated like button", "make a toast/snackbar slide in", "animate a drawer or modal", "animate list reordering or add/remove", "do a shared-element layout transition", or "polish UI feedback". Covers UI motion with Framer Motion (motion/react) and modern CSS.
|
||||
version: 0.1.0
|
||||
---
|
||||
|
||||
# Micro-interactions (UI Motion)
|
||||
|
||||
Small, functional motion that makes an interface feel responsive and alive: hover/press/focus feedback, toggles, toasts, drawers, and list/layout animation. The goal is feedback and continuity, not decoration.
|
||||
|
||||
## When to use
|
||||
|
||||
- Hover/press/focus feedback; toggles, checkboxes, like/heart buttons
|
||||
- Toasts/snackbars, drawers, modals, tooltips, accordions (enter/exit)
|
||||
- List add/remove/reorder; shared-element ("magic move") layout transitions
|
||||
- Loading → success → error state transitions
|
||||
|
||||
## Principles (apply to all of it)
|
||||
|
||||
- Duration: UI micro-interactions live in **100–250ms**. Anything over ~400ms feels laggy for a click response.
|
||||
- Animate `transform` and `opacity` only — they are GPU-composited (no layout/paint). Avoid animating `width/height/top/left`; use `scale` or layout animation instead.
|
||||
- Give **instant** press feedback: `scale: 0.96` on tap with a fast spring.
|
||||
- Asymmetric timing: enter slightly slower (ease-out), exit faster (ease-in). Things should arrive gracefully and leave promptly.
|
||||
- Respect `prefers-reduced-motion`: gate non-essential motion; keep opacity changes, drop large movement.
|
||||
- Easing defaults: ease-out for entrances `cubic-bezier(0.16, 1, 0.3, 1)`; a tasteful overshoot is `cubic-bezier(0.34, 1.56, 0.64, 1)`; standard move `cubic-bezier(0.4, 0, 0.2, 1)`.
|
||||
|
||||
## Framer Motion (motion/react) essentials
|
||||
|
||||
As of v11+, the package is imported as `motion/react` (the `framer-motion` name still works).
|
||||
|
||||
### Gestures and springs
|
||||
|
||||
```jsx
|
||||
import { motion } from "motion/react";
|
||||
|
||||
<motion.button
|
||||
whileHover={{ scale: 1.03 }}
|
||||
whileTap={{ scale: 0.96 }}
|
||||
whileFocus={{ boxShadow: "0 0 0 3px rgba(59,130,246,.5)" }}
|
||||
transition={{ type: "spring", stiffness: 400, damping: 30 }}
|
||||
/>
|
||||
```
|
||||
|
||||
Spring intuition: higher `stiffness` = faster; higher `damping` = less bounce. `stiffness: 400, damping: 30` is a snappy UI default. For visible bounce, lower damping (e.g. `damping: 12`).
|
||||
|
||||
### Enter / exit with AnimatePresence
|
||||
|
||||
Exit animations require `AnimatePresence` wrapping conditionally-rendered children, each with a stable `key`.
|
||||
|
||||
```jsx
|
||||
import { AnimatePresence, motion } from "motion/react";
|
||||
|
||||
<AnimatePresence>
|
||||
{open && (
|
||||
<motion.div
|
||||
key="panel"
|
||||
initial={{ opacity: 0, y: 8 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: 8 }}
|
||||
transition={{ duration: 0.2, ease: [0.16, 1, 0.3, 1] }}
|
||||
/>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
```
|
||||
|
||||
For toasts/lists, use `mode="popLayout"` so removed items don't hold space while exiting.
|
||||
|
||||
### Layout animation (the superpower)
|
||||
|
||||
`layout` automatically animates any layout change (position/size) using transforms — perfect for reordering, expanding cards, and grid<->list.
|
||||
|
||||
```jsx
|
||||
<motion.li layout transition={{ type: "spring", stiffness: 500, damping: 40 }} />
|
||||
```
|
||||
|
||||
Shared-element transition across components: give two elements the same `layoutId` and Framer Motion animates between them as one mounts and the other unmounts.
|
||||
|
||||
```jsx
|
||||
{!open && <motion.div layoutId="card" onClick={() => setOpen(true)} />}
|
||||
<AnimatePresence>
|
||||
{open && <motion.div layoutId="card" />} {/* "magic moves" from the source */}
|
||||
</AnimatePresence>
|
||||
```
|
||||
|
||||
Gotcha: a plain `layout` element distorts `border-radius` and text during scale. Add `layout` to direct children that should counter-scale, and prefer `borderRadius`/`boxShadow` as motion values, or use `layout="position"` to animate position only.
|
||||
|
||||
## Pure CSS path (no JS, including discrete properties)
|
||||
|
||||
Modern CSS can animate enter/exit and even `display` toggles without a library.
|
||||
|
||||
```css
|
||||
.toast {
|
||||
transition: opacity 0.2s ease, transform 0.2s ease;
|
||||
/* allow animating to/from display:none and from initial render */
|
||||
transition-behavior: allow-discrete;
|
||||
}
|
||||
.toast[hidden] { display: none; }
|
||||
|
||||
/* animate FROM these values on first render / when entering */
|
||||
@starting-style {
|
||||
.toast { opacity: 0; transform: translateY(8px); }
|
||||
}
|
||||
```
|
||||
|
||||
`@starting-style` defines the "before-open" values so an element animates in on first appearance; `transition-behavior: allow-discrete` lets `display` (and `overlay` for popovers/dialogs) participate so exit animations run before the element is removed. Baseline in Chrome/Edge/Safari; provide a no-animation fallback for older browsers.
|
||||
|
||||
Always include a reduced-motion guard:
|
||||
|
||||
```css
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## State, not just decoration
|
||||
|
||||
Loading → success → error should be one continuous motion (e.g. a button morphs spinner → checkmark), not a jump cut. Keep the element mounted and animate between states so the eye tracks the same object.
|
||||
|
||||
## Deliver & verify (standalone HTML)
|
||||
|
||||
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
|
||||
|
||||
For a self-contained interaction demo (toggle, like button, toast, drawer) the deliverable is **one HTML file that opens directly in a browser**. Pure-CSS interactions ship as-is; for a Framer Motion demo, load React + `motion` from CDN (`esm.sh`) into one inline module — no build step. One file is the right tier; don't reach for a bundler.
|
||||
|
||||
**Output contract:**
|
||||
- One `.html` file: your markup plus either CSS transitions/`@starting-style` or an inline `<script type="module">` importing `motion` from CDN.
|
||||
- A way to land on the **resolved end state** for a screenshot — interactions are state-driven, not time-driven, so freeze the state rather than a clock.
|
||||
|
||||
**Seek harness — pin a deterministic state.** A micro-interaction's "frames" are its states (idle / hover / pressed / open). `?state=open` applies the target state on load so a screenshot captures it settled:
|
||||
|
||||
```html
|
||||
<script>
|
||||
const s = new URLSearchParams(location.search).get("state");
|
||||
if (s) document.documentElement.dataset.state = s; // CSS keys off [data-state="open"]
|
||||
// Framer Motion: set the controlled prop from `s` (e.g. const [open]=useState(s==="open"))
|
||||
// For a CSS @keyframes loop instead, freeze it: el.style.animationDelay=(-N)+"s"; el.style.animationPlayState="paused";
|
||||
window.__ready = true;
|
||||
</script>
|
||||
```
|
||||
|
||||
**Verify loop — render → set state → screenshot → check:** open each meaningful state (`?state=idle`, `?state=hover`, `?state=open`), screenshot, and check **fidelity** (press feedback reads instant, exit runs before unmount) plus **artifacts** (`layout` distorting `border-radius`/text, toast holding space after exit, FOUC, jank). Any headless tool works:
|
||||
|
||||
```bash
|
||||
npx playwright screenshot --wait-for-timeout=400 "file://$PWD/demo.html?state=open" open.png
|
||||
```
|
||||
|
||||
**Before you finish:**
|
||||
1. Opens standalone — no console errors, CDN React/`motion` (if used) resolves.
|
||||
2. The `?state=` (or controlled-prop) freeze lands a deterministic, settled state.
|
||||
3. Screenshotted across states — idle / active / open — matches the brief, no artifacts.
|
||||
4. `prefers-reduced-motion` honored — large movement dropped, opacity/feedback kept.
|
||||
5. Easing is intentional — enter ease-out, exit ease-in, durations in the 100–250ms band.
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Need | Approach |
|
||||
|------|----------|
|
||||
| Press feedback | `whileTap={{ scale: 0.96 }}` spring 400/30 |
|
||||
| Enter/exit | `AnimatePresence` + `initial/animate/exit` |
|
||||
| Reorder / resize | `layout` prop (spring) |
|
||||
| Magic move | shared `layoutId` |
|
||||
| Toast stack | `AnimatePresence mode="popLayout"` |
|
||||
| No-JS enter | `@starting-style` + transition |
|
||||
| Animate to display:none | `transition-behavior: allow-discrete` |
|
||||
| Accessibility | `prefers-reduced-motion` guard always |
|
||||
|
||||
## Reference files
|
||||
|
||||
- `references/framer-motion-recipes.md` — variants + stagger, `AnimatePresence` modes, `layout`/`layoutId` magic move, `Reorder` drag-to-sort, drag constraints, gesture composition, and `useReducedMotion`.
|
||||
- `references/css-recipes.md` — `@starting-style`, `transition-behavior: allow-discrete`, popover/dialog exit animation, keyframe spinners/toggles, `@property` for animatable custom properties, and `prefers-reduced-motion` patterns.
|
||||
@@ -0,0 +1,142 @@
|
||||
# CSS Micro-interaction Recipes
|
||||
|
||||
Modern CSS handles most UI motion with zero JavaScript, including enter/exit and `display` toggles. Baseline-available in current Chrome/Edge/Safari/Firefox (verify `@starting-style` and `allow-discrete` for your support floor; degrade to instant show/hide otherwise).
|
||||
|
||||
## Enter animation on first render: @starting-style
|
||||
|
||||
`@starting-style` supplies the values an element transitions FROM the first time it renders (or becomes shown). Without it, there is no "previous" state to transition from, so newly-inserted elements snap in.
|
||||
|
||||
```css
|
||||
.menu {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
transition: opacity 0.2s ease, transform 0.2s ease;
|
||||
}
|
||||
@starting-style {
|
||||
.menu { opacity: 0; transform: translateY(-8px); }
|
||||
}
|
||||
```
|
||||
|
||||
## Animating to/from display:none: transition-behavior: allow-discrete
|
||||
|
||||
`display` and `content-visibility` are discrete properties — normally they flip instantly, killing exit animations. `allow-discrete` lets them flip at the correct moment (kept visible during exit, swapped at the end).
|
||||
|
||||
```css
|
||||
.drawer {
|
||||
transition:
|
||||
transform 0.25s ease,
|
||||
opacity 0.25s ease,
|
||||
display 0.25s allow-discrete; /* keep displayed through the exit */
|
||||
}
|
||||
.drawer[hidden] { /* closed state */
|
||||
opacity: 0;
|
||||
transform: translateX(100%);
|
||||
display: none;
|
||||
}
|
||||
@starting-style {
|
||||
.drawer:not([hidden]) { opacity: 0; transform: translateX(100%); }
|
||||
}
|
||||
```
|
||||
|
||||
Shorthand alternative: `transition-behavior: allow-discrete;` applies to all discrete properties in the `transition` list.
|
||||
|
||||
## Popover / dialog exit animation (top-layer)
|
||||
|
||||
Native `popover` and `<dialog>` live in the top layer via the `overlay` property, which is also discrete — animate it too:
|
||||
|
||||
```css
|
||||
[popover] {
|
||||
opacity: 0;
|
||||
transform: scale(0.95);
|
||||
transition: opacity 0.2s, transform 0.2s, overlay 0.2s allow-discrete, display 0.2s allow-discrete;
|
||||
}
|
||||
[popover]:popover-open { opacity: 1; transform: scale(1); }
|
||||
@starting-style {
|
||||
[popover]:popover-open { opacity: 0; transform: scale(0.95); }
|
||||
}
|
||||
```
|
||||
|
||||
This gives a fully CSS-driven open AND close animation for `<button popovertarget>` popovers with no JS.
|
||||
|
||||
## Press / hover / focus feedback
|
||||
|
||||
```css
|
||||
.btn {
|
||||
transition: transform 0.12s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease;
|
||||
}
|
||||
.btn:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(0,0,0,.15); }
|
||||
.btn:active { transform: translateY(0) scale(0.97); transition-duration: 0.06s; } /* snappy press */
|
||||
.btn:focus-visible { outline: 2px solid #3b82f6; outline-offset: 2px; }
|
||||
```
|
||||
|
||||
Use `:focus-visible` (not `:focus`) so keyboard users get a ring but mouse clicks don't.
|
||||
|
||||
## Animated toggle / switch
|
||||
|
||||
```css
|
||||
.switch { width: 44px; height: 24px; border-radius: 999px; background: #cbd5e1;
|
||||
transition: background 0.2s ease; }
|
||||
.switch[aria-checked="true"] { background: #22c55e; }
|
||||
.switch::after {
|
||||
content: ""; width: 20px; height: 20px; border-radius: 50%; background: #fff;
|
||||
transform: translateX(2px);
|
||||
transition: transform 0.22s cubic-bezier(0.34, 1.56, 0.64, 1);
|
||||
}
|
||||
.switch[aria-checked="true"]::after { transform: translateX(22px); }
|
||||
```
|
||||
|
||||
The `cubic-bezier(0.34, 1.56, 0.64, 1)` overshoot gives the knob a satisfying snap.
|
||||
|
||||
## Loading spinner and pulse
|
||||
|
||||
```css
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.spinner { animation: spin 0.8s linear infinite; }
|
||||
|
||||
@keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.5; } }
|
||||
.skeleton { animation: pulse 1.5s ease-in-out infinite; }
|
||||
```
|
||||
|
||||
## Animatable custom properties with @property
|
||||
|
||||
Plain CSS variables animate discretely. Register them with `@property` to give them a type so they interpolate smoothly — enables gradient angle, number counters, and themed motion.
|
||||
|
||||
```css
|
||||
@property --angle { syntax: "<angle>"; inherits: false; initial-value: 0deg; }
|
||||
|
||||
.gradient-border {
|
||||
background: conic-gradient(from var(--angle), #6366f1, #ec4899, #6366f1);
|
||||
transition: --angle 0.4s ease;
|
||||
}
|
||||
.gradient-border:hover { --angle: 360deg; }
|
||||
```
|
||||
|
||||
## Accordion height (modern: interpolate-size)
|
||||
|
||||
Animating `height: auto` historically required JS measurement. With `interpolate-size: allow-keywords`, transitions to/from intrinsic sizes work:
|
||||
|
||||
```css
|
||||
:root { interpolate-size: allow-keywords; }
|
||||
.accordion__panel {
|
||||
height: 0; overflow: hidden;
|
||||
transition: height 0.3s ease;
|
||||
}
|
||||
.accordion__panel[data-open] { height: auto; }
|
||||
```
|
||||
|
||||
Fallback for unsupported browsers: animate `grid-template-rows: 0fr -> 1fr` on a wrapper.
|
||||
|
||||
## Reduced motion (always include)
|
||||
|
||||
```css
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
scroll-behavior: auto !important;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Then selectively re-enable essential, low-motion feedback (e.g. opacity-only fades) inside the same query if needed. The principle: never remove feedback entirely, just remove large/spatial motion.
|
||||
@@ -0,0 +1,187 @@
|
||||
# Framer Motion Recipes
|
||||
|
||||
Import from `motion/react` (v11+). All examples are React + Framer Motion.
|
||||
|
||||
```jsx
|
||||
import { motion, AnimatePresence, Reorder, useReducedMotion, useDragControls } from "motion/react";
|
||||
```
|
||||
|
||||
## Variants and staggered children
|
||||
|
||||
Variants are named animation states a parent can propagate to children, enabling orchestration like staggering without per-child timing math.
|
||||
|
||||
```jsx
|
||||
const list = {
|
||||
hidden: { opacity: 0 },
|
||||
show: {
|
||||
opacity: 1,
|
||||
transition: { staggerChildren: 0.06, delayChildren: 0.1 },
|
||||
},
|
||||
};
|
||||
const item = {
|
||||
hidden: { opacity: 0, y: 12 },
|
||||
show: { opacity: 1, y: 0, transition: { type: "spring", stiffness: 500, damping: 30 } },
|
||||
};
|
||||
|
||||
<motion.ul variants={list} initial="hidden" animate="show">
|
||||
{items.map((t) => (
|
||||
<motion.li key={t.id} variants={item}>{t.label}</motion.li>
|
||||
))}
|
||||
</motion.ul>
|
||||
```
|
||||
|
||||
`staggerDirection: -1` staggers from last to first. `when: "beforeChildren"` / `"afterChildren"` sequences parent vs children.
|
||||
|
||||
## AnimatePresence modes
|
||||
|
||||
```jsx
|
||||
<AnimatePresence mode="wait"> {/* outgoing finishes before incoming starts (route/tab switches) */}
|
||||
<motion.div key={tab} initial={{opacity:0}} animate={{opacity:1}} exit={{opacity:0}} />
|
||||
</AnimatePresence>
|
||||
```
|
||||
|
||||
Modes:
|
||||
- default (`"sync"`) — incoming and outgoing animate simultaneously.
|
||||
- `"wait"` — finish exit before enter (single-element swaps like tabs/pages).
|
||||
- `"popLayout"` — exiting items are popped from layout flow so siblings re-flow immediately (toast stacks, removing list items). Children must be capable of `layout`.
|
||||
|
||||
Require a unique, stable `key` on each child. To run exit on initial mount too, that is not needed; to suppress enter animation on first render set `<AnimatePresence initial={false}>`.
|
||||
|
||||
## Toast stack (popLayout + layout)
|
||||
|
||||
```jsx
|
||||
function Toasts({ toasts }) {
|
||||
return (
|
||||
<div className="toast-region">
|
||||
<AnimatePresence mode="popLayout">
|
||||
{toasts.map((t) => (
|
||||
<motion.div
|
||||
key={t.id}
|
||||
layout
|
||||
initial={{ opacity: 0, y: 24, scale: 0.9 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.9, transition: { duration: 0.15 } }}
|
||||
transition={{ type: "spring", stiffness: 500, damping: 40 }}
|
||||
>
|
||||
{t.message}
|
||||
</motion.div>
|
||||
))}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
`layout` makes remaining toasts slide up smoothly when one is dismissed.
|
||||
|
||||
## Magic-move / shared-element layout
|
||||
|
||||
```jsx
|
||||
function Gallery() {
|
||||
const [active, setActive] = useState(null);
|
||||
return (
|
||||
<>
|
||||
<div className="grid">
|
||||
{photos.map((p) => (
|
||||
<motion.img key={p.id} layoutId={`photo-${p.id}`} src={p.thumb}
|
||||
onClick={() => setActive(p)} />
|
||||
))}
|
||||
</div>
|
||||
<AnimatePresence>
|
||||
{active && (
|
||||
<motion.div className="backdrop" onClick={() => setActive(null)}
|
||||
initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
|
||||
<motion.img layoutId={`photo-${active.id}`} src={active.full} />
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Matching `layoutId` makes the thumbnail visually fly to the lightbox and back.
|
||||
|
||||
## Drag-to-reorder list
|
||||
|
||||
`Reorder` handles pointer drag, axis locking, and live reordering with layout animation built in.
|
||||
|
||||
```jsx
|
||||
function SortableList({ items, setItems }) {
|
||||
return (
|
||||
<Reorder.Group axis="y" values={items} onReorder={setItems}>
|
||||
{items.map((item) => (
|
||||
<Reorder.Item key={item} value={item}
|
||||
whileDrag={{ scale: 1.03, boxShadow: "0 8px 24px rgba(0,0,0,.18)" }}>
|
||||
{item}
|
||||
</Reorder.Item>
|
||||
))}
|
||||
</Reorder.Group>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
For a dedicated drag handle, use `useDragControls`:
|
||||
|
||||
```jsx
|
||||
const controls = useDragControls();
|
||||
<Reorder.Item value={item} dragListener={false} dragControls={controls}>
|
||||
<span className="handle" onPointerDown={(e) => controls.start(e)}>⠿</span>
|
||||
{item.label}
|
||||
</Reorder.Item>
|
||||
```
|
||||
|
||||
## Drag with constraints and elastic
|
||||
|
||||
```jsx
|
||||
const ref = useRef(null);
|
||||
<div ref={ref} className="bounds">
|
||||
<motion.div drag dragConstraints={ref} dragElastic={0.2}
|
||||
dragTransition={{ bounceStiffness: 600, bounceDamping: 20 }} />
|
||||
</div>
|
||||
```
|
||||
|
||||
`dragElastic` (0–1) controls how far past constraints it can be pulled; `dragSnapToOrigin` returns it on release.
|
||||
|
||||
## Gesture composition (like button)
|
||||
|
||||
```jsx
|
||||
function Like() {
|
||||
const [liked, setLiked] = useState(false);
|
||||
return (
|
||||
<motion.button onClick={() => setLiked((v) => !v)} whileTap={{ scale: 0.85 }}>
|
||||
<motion.span
|
||||
animate={liked ? { scale: [1, 1.4, 1], color: "#ef4444" } : { scale: 1, color: "#9ca3af" }}
|
||||
transition={{ duration: 0.35, ease: "easeOut" }}
|
||||
>♥</motion.span>
|
||||
</motion.button>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Arrays of values (`scale: [1, 1.4, 1]`) are keyframes; control their spacing with `times: [0, 0.6, 1]`.
|
||||
|
||||
## Respecting reduced motion
|
||||
|
||||
```jsx
|
||||
function Panel() {
|
||||
const reduce = useReducedMotion();
|
||||
return (
|
||||
<motion.div
|
||||
initial={reduce ? false : { opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Wrap an app in `<MotionConfig reducedMotion="user">` to globally strip transform/layout animations for users who prefer reduced motion while keeping opacity.
|
||||
|
||||
## Performance notes
|
||||
|
||||
- Prefer `transform`/`opacity`; Framer Motion already uses transforms for `x/y/scale/rotate`.
|
||||
- For frequently-updated values (cursor follow, scroll), use `useMotionValue` + `useSpring` instead of React state to avoid re-renders.
|
||||
- `layout` is powerful but measure-heavy; avoid putting it on hundreds of simultaneously-animating nodes.
|
||||
|
||||
---
|
||||
Tune the timing and easing and a micro-interaction feels effortless. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=micro-interaction)** — the AI motion agent for editable, on-brand motion graphics.
|
||||
Whitespace-only changes.
@@ -0,0 +1,218 @@
|
||||
---
|
||||
name: page-transition-animation
|
||||
description: This skill should be used when the user asks to "animate page or route transitions", "add a page transition or crossfade between views", "animate route changes in Next.js App Router", "use the View Transitions API", "AnimatePresence exit doesn't fire on navigation", or "Framer Motion exit animation not working / exit animation before unmount in Next.js". Covers enter/exit page-transition animation with the View Transitions API and Framer Motion, for Next.js App Router and general SPA routing.
|
||||
version: 0.1.0
|
||||
---
|
||||
|
||||
# Page Transition Animation (Next.js App Router)
|
||||
|
||||
Implement page enter/exit transitions in the Next.js **App Router**, and fix the single most common failure: **Framer Motion `AnimatePresence` exit animations never fire on navigation**. The reason is structural — in the App Router, when navigating, Next.js unmounts the old route's content and mounts the new one almost immediately. `AnimatePresence` can only animate an exit if the *exiting element stays mounted* under a *persistent* `AnimatePresence` wrapper long enough to run the animation. Because the router swaps children out from under it, the exit is skipped. Two approaches solve this: a pathname-keyed `AnimatePresence` with the **FrozenRouter** pattern, or the **View Transitions API** (native / `next-view-transitions`).
|
||||
|
||||
## When to use
|
||||
|
||||
Use when adding animated page transitions in a Next.js App Router app, when a Framer Motion `exit` prop does nothing on route change, when an old page disappears instantly instead of animating out, when choosing between Framer Motion and the View Transitions API for Next.js, or when debugging why `AnimatePresence` won't animate between routes.
|
||||
|
||||
## Why exit doesn't fire (the core problem)
|
||||
|
||||
`AnimatePresence` detects removal of a *direct keyed child*. On App Router navigation:
|
||||
|
||||
1. The wrapper must persist across the navigation. If `AnimatePresence` lives in a component that itself unmounts, there is nothing left to run the exit.
|
||||
2. The child's `key` must change per route so AnimatePresence sees "old removed, new added".
|
||||
3. During the brief overlap, the *outgoing* subtree must still render its old content — but the App Router has already swapped the route context, so the outgoing tree would otherwise render the *new* page's data. This is what **FrozenRouter** fixes.
|
||||
|
||||
## Solution A: template.tsx + keyed AnimatePresence + FrozenRouter
|
||||
|
||||
`template.tsx` is the App Router's purpose-built hook for this: unlike `layout.tsx` (which persists), a **template remounts on every navigation**, giving each route a fresh instance — ideal for per-route enter animations. Combine it with a pathname-keyed `AnimatePresence` and FrozenRouter for clean exit + enter.
|
||||
|
||||
```tsx
|
||||
// app/template.tsx
|
||||
'use client';
|
||||
import { AnimatePresence } from 'framer-motion';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import { FrozenRouter } from './frozen-router';
|
||||
import { PageTransition } from './page-transition';
|
||||
|
||||
export default function Template({ children }: { children: React.ReactNode }) {
|
||||
const pathname = usePathname();
|
||||
return (
|
||||
<AnimatePresence mode="wait" initial={false}>
|
||||
{/* key on pathname so AnimatePresence sees old removed / new added */}
|
||||
<PageTransition key={pathname}>
|
||||
{/* FrozenRouter keeps the OUTGOING tree rendering its old content
|
||||
while it animates out */}
|
||||
<FrozenRouter>{children}</FrozenRouter>
|
||||
</PageTransition>
|
||||
</AnimatePresence>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// app/page-transition.tsx
|
||||
'use client';
|
||||
import { motion } from 'framer-motion';
|
||||
|
||||
export function PageTransition({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -12 }}
|
||||
transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
|
||||
>
|
||||
{children}
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// app/frozen-router.tsx
|
||||
'use client';
|
||||
import { useContext, useRef } from 'react';
|
||||
import {
|
||||
LayoutRouterContext,
|
||||
} from 'next/dist/shared/lib/app-router-context.shared-runtime';
|
||||
|
||||
// Freezes the router context so the exiting page keeps rendering its
|
||||
// OWN content during the exit animation instead of the next route's.
|
||||
export function FrozenRouter({ children }: { children: React.ReactNode }) {
|
||||
const context = useContext(LayoutRouterContext ?? {});
|
||||
const frozen = useRef(context).current;
|
||||
|
||||
return (
|
||||
<LayoutRouterContext.Provider value={frozen}>
|
||||
{children}
|
||||
</LayoutRouterContext.Provider>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
How it fits together:
|
||||
|
||||
- `mode="wait"` makes AnimatePresence fully finish the exit before mounting the new page. (Use the default mode if enter/exit should overlap/crossfade.)
|
||||
- `initial={false}` skips the enter animation on first load (optional).
|
||||
- `key={pathname}` is what makes AnimatePresence treat each route as a distinct presence.
|
||||
- `FrozenRouter` snapshots `LayoutRouterContext` so the outgoing subtree renders the *previous* route's content throughout the exit, instead of flashing the new route's content. Without it, exit either skips or shows the wrong content.
|
||||
|
||||
Note: `LayoutRouterContext` is a Next.js internal; its import path can change between Next versions. If the import breaks after an upgrade, that path is the thing to update.
|
||||
|
||||
## Solution B: native View Transitions API
|
||||
|
||||
The View Transitions API animates between two DOM states with the browser capturing before/after snapshots — no per-element exit components.
|
||||
|
||||
```css
|
||||
/* globals.css */
|
||||
@view-transition { navigation: auto; } /* opt MPA-style in (where supported) */
|
||||
|
||||
::view-transition-old(root) { animation: fade 0.25s both reverse; }
|
||||
::view-transition-new(root) { animation: fade 0.25s both; }
|
||||
@keyframes fade { from { opacity: 0; } to { opacity: 1; } }
|
||||
```
|
||||
|
||||
For SPA-style App Router navigations, wrap the router update:
|
||||
|
||||
```ts
|
||||
if (document.startViewTransition) {
|
||||
document.startViewTransition(() => router.push(href));
|
||||
} else {
|
||||
router.push(href);
|
||||
}
|
||||
```
|
||||
|
||||
### next-view-transitions library
|
||||
|
||||
`next-view-transitions` integrates the View Transitions API with the App Router's client navigation so it works out of the box:
|
||||
|
||||
```tsx
|
||||
// app/layout.tsx
|
||||
import { ViewTransitions } from 'next-view-transitions';
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<ViewTransitions>
|
||||
<html lang="en"><body>{children}</body></html>
|
||||
</ViewTransitions>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// use the library's Link instead of next/link
|
||||
import { Link } from 'next-view-transitions';
|
||||
<Link href="/about">About</Link>;
|
||||
```
|
||||
|
||||
Choose View Transitions for simple cross-page fades/morphs and shared-element transitions with minimal JS; choose Framer Motion when fine-grained, orchestrated, interruptible, or staggered exit animations are needed. View Transitions API browser support is still uneven, so provide a graceful fallback (the `if (document.startViewTransition)` guard).
|
||||
|
||||
## AnimatePresence debug checklist
|
||||
|
||||
When exit still won't fire, verify in order:
|
||||
|
||||
1. **Wrapper stays mounted.** `AnimatePresence` must live in something persistent — ideally `template.tsx`, or a layout-level client component — not inside the page that's unmounting.
|
||||
2. **Stable, changing key.** The animated child needs `key={pathname}` (or similar) so removal is detected. No key, or a key that doesn't change → no exit.
|
||||
3. **Direct motion descendant.** The element with the `exit` prop must be a `motion.*` component and a child of `AnimatePresence` (a non-motion wrapper in between can block detection).
|
||||
4. **`mode="wait"`** if old and new should not overlap; without it both render simultaneously and may jump.
|
||||
5. **FrozenRouter present** if the outgoing page flashes the new route's content during exit.
|
||||
6. **`'use client'`** on every file using AnimatePresence/usePathname/motion.
|
||||
7. **Single child at a time** under `mode="wait"` — AnimatePresence expects one keyed presence to swap.
|
||||
|
||||
## Deliver & verify (standalone HTML)
|
||||
|
||||
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
|
||||
|
||||
The real target is a Next.js app, but to *prove the transition shape* (the enter/exit curve, direction, crossfade) you can ship **one HTML file that opens directly in a browser** — two stub "pages" you toggle, animated with `motion` from CDN or the native View Transitions API. One file is the right tier for validating motion before wiring the router; don't stand up Next just to eyeball a fade.
|
||||
|
||||
**Output contract:**
|
||||
- One `.html` file: two view stubs and a toggle, animated with either an inline `<script type="module">` importing `motion`/React from CDN, or `document.startViewTransition` + `::view-transition-*` CSS.
|
||||
- A way to freeze the **resolved end state** — a route transition is state-driven (which view, mid-swap), so screenshot the state, not a clock.
|
||||
|
||||
**Seek harness — pin a transition phase.** `?view=b` mounts the destination view (or `?phase=exit` to hold the outgoing tree mid-animation) so a screenshot lands on a settled phase:
|
||||
|
||||
```html
|
||||
<script>
|
||||
const p = new URLSearchParams(location.search);
|
||||
document.documentElement.dataset.view = p.get("view") || "a"; // CSS/React keys off this
|
||||
// Framer Motion: set the controlled key/route from ?view; for mode="wait" the resolved end is the new page
|
||||
// View Transitions: screenshot the END state (snapshots are transient); or pause via emulate slow animations
|
||||
window.__ready = true;
|
||||
</script>
|
||||
```
|
||||
|
||||
**Verify loop — render → set phase → screenshot → check:** open source, mid, and destination (`?view=a`, `?phase=exit`, `?view=b`), screenshot each, and check **fidelity** (exit actually runs, direction/crossfade matches the brief, no `mode="wait"` lag) plus **artifacts** (outgoing tree flashing the new page's content, double-mount, FOUC, jank). Any headless tool works:
|
||||
|
||||
```bash
|
||||
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/transition.html?view=b" dest.png
|
||||
```
|
||||
|
||||
**Before you finish:**
|
||||
1. Opens standalone — no console errors, CDN `motion`/React (if used) resolves, `startViewTransition` guarded.
|
||||
2. The `?view=`/`?phase=` freeze lands a deterministic transition phase.
|
||||
3. Screenshotted at source / mid / destination — matches the brief, no content flash or skipped exit.
|
||||
4. `prefers-reduced-motion` honored — slide/translate dropped to a short crossfade.
|
||||
5. Easing is intentional — entrances ease-out, exits ease-in, durations ~0.2–0.4s (not laggy under `mode="wait"`).
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Need | Approach |
|
||||
|---|---|
|
||||
| Per-route enter animation | `app/template.tsx` (remounts each nav) |
|
||||
| Exit animation on nav | keyed `AnimatePresence mode="wait"` + FrozenRouter |
|
||||
| Outgoing page shows old content | FrozenRouter (snapshot `LayoutRouterContext`) |
|
||||
| Detect route change | `usePathname()` as the `key` |
|
||||
| Simple cross-page fade/morph | View Transitions API / next-view-transitions |
|
||||
| Shared element transition | `view-transition-name` CSS |
|
||||
| Skip first-load animation | `initial={false}` |
|
||||
|
||||
## Gotchas
|
||||
|
||||
- `layout.tsx` persists and will NOT remount per route — use `template.tsx` for per-route enter animations.
|
||||
- Omitting FrozenRouter makes the exiting page render the *new* route's content mid-animation (visible flash) or skip exit entirely.
|
||||
- `LayoutRouterContext` import path is a Next internal; it may change across versions — first thing to fix after an upgrade.
|
||||
- Without `key={pathname}`, AnimatePresence sees the same child and never triggers exit.
|
||||
- `mode="wait"` waits for exit before enter; overusing it on slow exits makes navigation feel laggy — tune durations (~0.2-0.4s).
|
||||
- View Transitions API lacks full browser support; always guard `document.startViewTransition`.
|
||||
- Every transition file needs `'use client'`; server components can't use AnimatePresence/usePathname.
|
||||
|
||||
## Reference files
|
||||
|
||||
- `references/full-examples.md` — directional/slide transitions, shared-element View Transitions with `view-transition-name`, a non-`mode="wait"` crossfade variant, loading-state transitions with `loading.tsx`, and a complete working App Router folder layout.
|
||||
@@ -0,0 +1,176 @@
|
||||
# Full examples and variants
|
||||
|
||||
## Working folder layout
|
||||
|
||||
```
|
||||
app/
|
||||
layout.tsx # persistent shell (html/body, providers)
|
||||
template.tsx # remounts per route -> hosts AnimatePresence
|
||||
page-transition.tsx # motion wrapper (enter/exit variants)
|
||||
frozen-router.tsx # FrozenRouter (LayoutRouterContext snapshot)
|
||||
page.tsx # home
|
||||
about/page.tsx
|
||||
globals.css
|
||||
```
|
||||
|
||||
## Directional slide transitions
|
||||
|
||||
Track direction by comparing route depth or a route order map, then feed it to variants.
|
||||
|
||||
```tsx
|
||||
// app/page-transition.tsx
|
||||
'use client';
|
||||
import { motion } from 'framer-motion';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import { useRef } from 'react';
|
||||
|
||||
const order = ['/', '/about', '/work', '/contact'];
|
||||
|
||||
export function PageTransition({ children }: { children: React.ReactNode }) {
|
||||
const pathname = usePathname();
|
||||
const prev = useRef(pathname);
|
||||
const dir =
|
||||
order.indexOf(pathname) > order.indexOf(prev.current) ? 1 : -1;
|
||||
prev.current = pathname;
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
custom={dir}
|
||||
variants={{
|
||||
initial: (d: number) => ({ opacity: 0, x: 40 * d }),
|
||||
animate: { opacity: 1, x: 0 },
|
||||
exit: (d: number) => ({ opacity: 0, x: -40 * d }),
|
||||
}}
|
||||
initial="initial"
|
||||
animate="animate"
|
||||
exit="exit"
|
||||
transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
|
||||
>
|
||||
{children}
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Crossfade variant (no mode="wait")
|
||||
|
||||
Omit `mode="wait"` so old and new overlap. Stack them absolutely to avoid layout jump.
|
||||
|
||||
```tsx
|
||||
// app/template.tsx
|
||||
'use client';
|
||||
import { AnimatePresence, motion } from 'framer-motion';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import { FrozenRouter } from './frozen-router';
|
||||
|
||||
export default function Template({ children }: { children: React.ReactNode }) {
|
||||
const pathname = usePathname();
|
||||
return (
|
||||
<AnimatePresence initial={false}>
|
||||
<motion.div
|
||||
key={pathname}
|
||||
style={{ gridArea: '1 / 1' }} // overlap in a 1-cell grid parent
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.35 }}
|
||||
>
|
||||
<FrozenRouter>{children}</FrozenRouter>
|
||||
</motion.div>
|
||||
</AnimatePresence>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Wrap the template output's parent in `display: grid` so both stacked children occupy `grid-area: 1 / 1`.
|
||||
|
||||
## Shared-element transition (View Transitions API)
|
||||
|
||||
Give the same logical element the same `view-transition-name` on both pages; the browser morphs between them.
|
||||
|
||||
```tsx
|
||||
// list page
|
||||
<img src={cover} style={{ viewTransitionName: `cover-${id}` }} />
|
||||
// detail page
|
||||
<img src={cover} style={{ viewTransitionName: `cover-${id}` }} />
|
||||
```
|
||||
|
||||
```css
|
||||
::view-transition-old(root),
|
||||
::view-transition-new(root) { animation-duration: 0.3s; }
|
||||
/* the named element animates automatically between its two positions */
|
||||
```
|
||||
|
||||
With `next-view-transitions`, use its `<Link>` and the morph happens on navigation. Each `view-transition-name` must be unique on the page at a time.
|
||||
|
||||
## loading.tsx + transitions
|
||||
|
||||
`loading.tsx` shows an instant Suspense fallback during server work. To animate it, make the fallback a motion component; it mounts/unmounts within the same template-driven AnimatePresence flow.
|
||||
|
||||
```tsx
|
||||
// app/work/loading.tsx
|
||||
'use client';
|
||||
import { motion } from 'framer-motion';
|
||||
export default function Loading() {
|
||||
return (
|
||||
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
|
||||
Loading…
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Reduced-motion
|
||||
|
||||
```tsx
|
||||
'use client';
|
||||
import { useReducedMotion, motion } from 'framer-motion';
|
||||
|
||||
export function PageTransition({ children }: { children: React.ReactNode }) {
|
||||
const reduce = useReducedMotion();
|
||||
return (
|
||||
<motion.div
|
||||
initial={reduce ? false : { opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={reduce ? { opacity: 1 } : { opacity: 0, y: -12 }}
|
||||
transition={{ duration: reduce ? 0 : 0.3 }}
|
||||
>
|
||||
{children}
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
For the View Transitions API, gate with CSS:
|
||||
|
||||
```css
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
::view-transition-old(root),
|
||||
::view-transition-new(root) { animation: none; }
|
||||
}
|
||||
```
|
||||
|
||||
## FrozenRouter import note across versions
|
||||
|
||||
The internal context import has shifted across Next versions, e.g.:
|
||||
|
||||
```ts
|
||||
// commonly:
|
||||
import { LayoutRouterContext } from 'next/dist/shared/lib/app-router-context.shared-runtime';
|
||||
```
|
||||
|
||||
If an upgrade breaks the import, search `node_modules/next/dist/shared/lib/` for `app-router-context` and update the path. Because it is internal, pin awareness of this in any upgrade checklist.
|
||||
|
||||
## Framer Motion vs View Transitions decision
|
||||
|
||||
| Factor | Framer Motion | View Transitions API |
|
||||
|---|---|---|
|
||||
| Browser support | Broad (JS lib) | Uneven; needs fallback |
|
||||
| Orchestration/stagger | Excellent | Limited |
|
||||
| Interruptible exits | Yes | Limited |
|
||||
| Shared element morph | Manual (layoutId) | Native, simple |
|
||||
| Bundle cost | Adds library | Minimal/native |
|
||||
| Setup complexity | Medium (FrozenRouter) | Low (next-view-transitions) |
|
||||
|
||||
---
|
||||
Freeze the outgoing route and exit transitions finally fire as intended. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=page-transition-animation)** — the AI motion agent for editable, on-brand motion graphics.
|
||||
Whitespace-only changes.
@@ -0,0 +1,167 @@
|
||||
---
|
||||
name: svg-animation
|
||||
description: This skill should be used when the user asks to "animate an SVG", "make a line draw itself on", "do a stroke draw-on / signature animation", "morph one shape into another", "move an element along a path", "animate an icon/logo", or "animate an SVG gradient or filter". Covers stroke-dashoffset draw-on, path morphing, motion-along-path, and animated icons/gradients/filters via CSS, SMIL, and GSAP.
|
||||
version: 0.1.0
|
||||
---
|
||||
|
||||
# SVG Animation
|
||||
|
||||
Crisp, lightweight, infinitely scalable vector motion — ideal for icons, illustrations, logos, and data marks. SVG can be animated three ways: CSS (declarative, simple), SMIL (`<animate>` inside the SVG), and JS (GSAP/Web Animations, for control and morphing). Choose per task; the techniques below say which.
|
||||
|
||||
## When to use
|
||||
|
||||
- Stroke "draw-on" of icons, illustrations, signatures, maps
|
||||
- Shape/path morphing and animated icon state changes (menu ↔ close, play ↔ pause)
|
||||
- Moving an element along a path (motion path)
|
||||
- Animated gradients, filters (glow, displacement), and animated logos
|
||||
|
||||
## Core techniques
|
||||
|
||||
### Stroke draw-on (the staple)
|
||||
|
||||
Draw the dash array as long as the path, offset it fully (invisible), then animate the offset to 0.
|
||||
|
||||
```css
|
||||
.path {
|
||||
stroke-dasharray: var(--len);
|
||||
stroke-dashoffset: var(--len);
|
||||
animation: draw 1.4s ease forwards;
|
||||
}
|
||||
@keyframes draw { to { stroke-dashoffset: 0; } }
|
||||
```
|
||||
|
||||
Getting the length:
|
||||
- JS (most reliable): `const len = path.getTotalLength(); path.style.setProperty("--len", len);`
|
||||
- No-JS trick: set `pathLength="1"` on the `<path>`, then `stroke-dasharray: 1; stroke-dashoffset: 1;` and animate to `0`. This normalizes any path to a 0–1 length so no measurement is needed.
|
||||
|
||||
Reverse (erase) by animating offset from 0 back to `len`. Stagger multiple paths with `animation-delay`. Direction of drawing follows the path's point order; reverse it in the editor or negate the offset sign if it draws "backwards".
|
||||
|
||||
### Morphing one path into another
|
||||
|
||||
Paths interpolate point-by-point, so a naive morph requires both `d` attributes to have the **same number and type of commands**. Two robust approaches:
|
||||
|
||||
- **GSAP MorphSVG** (free as of GSAP 3.12) — handles mismatched point counts automatically and finds a good mapping:
|
||||
|
||||
```js
|
||||
gsap.registerPlugin(MorphSVGPlugin);
|
||||
gsap.to("#start", { morphSVG: "#end", duration: 0.8, ease: "power2.inOut" });
|
||||
// Convert any shape to a morph-able path:
|
||||
MorphSVGPlugin.convertToPath("circle, rect, ellipse, line, polygon");
|
||||
```
|
||||
|
||||
- **Flubber** (small standalone lib) — generates interpolators without GSAP, good with React/Framer Motion:
|
||||
|
||||
```js
|
||||
import { interpolate } from "flubber";
|
||||
const interpolator = interpolate(pathA, pathB, { maxSegmentLength: 2 });
|
||||
// interpolator(0) === pathA, interpolator(1) === pathB; feed t into a tween.
|
||||
```
|
||||
|
||||
For hand-authored morphs (icon toggles), keep both paths with identical command structure and animate `d` directly via Web Animations or CSS (`d` is animatable in modern browsers via `path("...")`).
|
||||
|
||||
### Motion along a path
|
||||
|
||||
- **GSAP MotionPath** (preferred — control, alignment, scrub):
|
||||
|
||||
```js
|
||||
gsap.registerPlugin(MotionPathPlugin);
|
||||
gsap.to("#rocket", {
|
||||
duration: 4, repeat: -1, ease: "none",
|
||||
motionPath: { path: "#track", align: "#track", autoRotate: true, alignOrigin: [0.5, 0.5] },
|
||||
});
|
||||
```
|
||||
|
||||
`autoRotate: true` orients the object to the path tangent; `align` makes coordinates relative to the path element.
|
||||
|
||||
- **SMIL** (no JS):
|
||||
|
||||
```svg
|
||||
<path id="track" d="M10,80 C40,10 120,10 150,80" fill="none"/>
|
||||
<circle r="6" fill="#3b82f6">
|
||||
<animateMotion dur="3s" repeatCount="indefinite" rotate="auto">
|
||||
<mpath href="#track"/>
|
||||
</animateMotion>
|
||||
</circle>
|
||||
```
|
||||
|
||||
- **CSS** offset-path (modern, declarative): `offset-path: path("M10,80 C..."); animation: move 3s linear infinite;` with `@keyframes move { to { offset-distance: 100%; } }` and `offset-rotate: auto`.
|
||||
|
||||
### Animated gradients and filters
|
||||
|
||||
Gradients: animate `gradientTransform` or stop offsets. A sheen sweep:
|
||||
|
||||
```svg
|
||||
<linearGradient id="sheen">
|
||||
<stop offset="0%" stop-color="#fff" stop-opacity="0"/>
|
||||
<stop offset="50%" stop-color="#fff" stop-opacity=".8"/>
|
||||
<stop offset="100%" stop-color="#fff" stop-opacity="0"/>
|
||||
<animateTransform attributeName="gradientTransform" type="translate"
|
||||
from="-1 0" to="1 0" dur="2s" repeatCount="indefinite"/>
|
||||
</linearGradient>
|
||||
```
|
||||
|
||||
Filters: animate `feDisplacementMap` `scale` for gooey/wobble, `feGaussianBlur` `stdDeviation` for focus pulls, or `feColorMatrix`/`feFlood` for glow. Filters are paint-heavy — animate sparingly and prefer `transform`/`opacity` where possible.
|
||||
|
||||
## Implementation choice (pick fast)
|
||||
|
||||
| Need | Use |
|
||||
|------|-----|
|
||||
| Single declarative draw/fade | CSS |
|
||||
| Self-contained, no JS bundle | SMIL (`<animate*>` in the SVG) |
|
||||
| Coordinated, scrubbable, scroll-tied | GSAP |
|
||||
| Mismatched-point morph | GSAP MorphSVG or Flubber |
|
||||
| Path following with rotation | GSAP MotionPath / CSS offset-path |
|
||||
|
||||
SMIL caveat: not supported in IE/old Edge and historically deprecation-flagged; for max reach or scroll-syncing, prefer CSS or JS. SMIL is still fine for self-contained icon assets in evergreen browsers.
|
||||
|
||||
## Authoring and optimization
|
||||
|
||||
- Build/clean with **SVGO**: keep `viewBox`, drop editor metadata, but disable `cleanupIds`/`removeViewBox` and any plugin that renames IDs you reference from CSS/JS/SMIL. Disable `mergePaths` and `convertShapeToPath` if you animate individual sub-paths or shapes.
|
||||
- Inline the SVG in the DOM (not `<img src>`) so CSS/JS can reach its internals; `<img>`-embedded SVG can only self-animate via internal SMIL/CSS.
|
||||
- Set explicit `viewBox` and avoid fixed `width`/`height` so the asset scales fluidly.
|
||||
- For draw-on, ensure paths are actual strokes (`fill:none; stroke:...`), not filled outlines — dashoffset only affects strokes.
|
||||
- Respect `prefers-reduced-motion`: gate looping/large motion; keep a static final state.
|
||||
|
||||
## Deliver & verify (standalone HTML)
|
||||
|
||||
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
|
||||
|
||||
For a self-contained icon/logo/draw-on the deliverable is **one HTML file that opens directly in a browser** — inline the SVG in the markup, drive the animation with one mechanism, no build step. One file is the right tier for a vector asset; don't reach for a bundler.
|
||||
|
||||
**Output contract:**
|
||||
- One `.html` file: inline `<svg>`, plus CSS `@keyframes` / a `<script>` with GSAP from CDN / SMIL `<animate*>` — pick one driver.
|
||||
- Include the seek harness matching that driver so any moment can be frozen for a screenshot.
|
||||
|
||||
**Seek harness — freeze an exact moment.** `?t=N` seeks and pauses so a screenshot lands on a still frame. Use the mechanism that matches how the SVG animates:
|
||||
|
||||
```html
|
||||
<script>
|
||||
const t = new URLSearchParams(location.search).get("t");
|
||||
if (t !== null) {
|
||||
const N = parseFloat(t);
|
||||
// SMIL: pause the SVG's own clock and scrub it
|
||||
const svg = document.querySelector("svg");
|
||||
svg.pauseAnimations(); svg.setCurrentTime(N);
|
||||
// CSS @keyframes draw-on: el.style.animationDelay=(-N)+"s"; el.style.animationPlayState="paused";
|
||||
// GSAP timeline: tl.pause(); tl.seek(N);
|
||||
}
|
||||
window.__ready = true;
|
||||
</script>
|
||||
```
|
||||
|
||||
**Verify loop — render → freeze → screenshot → check:** open the file at start / mid / end (`?t=0`, `?t=<dur/2>`, `?t=<dur>`), screenshot each, and check **fidelity** (stroke draws in the right direction, morph endpoints clean) plus **artifacts** (path clipped by `viewBox`, stroke vanishing from a stale dashoffset, FOUC, jank at the morph seam). Any headless tool works:
|
||||
|
||||
```bash
|
||||
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/icon.html?t=0.7" frame-mid.png
|
||||
```
|
||||
|
||||
**Before you finish:**
|
||||
1. Opens standalone — no console errors, inline SVG reachable, CDN (if any) loads.
|
||||
2. The seek mechanism for your driver freezes a deterministic frame.
|
||||
3. Screenshotted at start / mid / end — matches the brief, no clipping or off-`viewBox` strokes.
|
||||
4. `prefers-reduced-motion` honored — looping/large motion gated, static final state kept.
|
||||
5. Easing is intentional — `ease`/GSAP ease chosen on purpose, no accidental `linear` draw-on.
|
||||
|
||||
## Reference files
|
||||
|
||||
- `references/svg-techniques.md` — full dashoffset math and `getTotalLength` gotchas, the `pathLength="1"` normalization, GSAP MorphSVG vs Flubber decision guide with code, an icon-toggle morph (hamburger↔close), MotionPath/offset-path details, SMIL-vs-CSS-vs-JS tradeoffs, and an SVGO config tuned for animation.
|
||||
@@ -0,0 +1,214 @@
|
||||
# SVG Animation Techniques (detailed)
|
||||
|
||||
## 1. Stroke draw-on: the math
|
||||
|
||||
`stroke-dasharray` defines a dash pattern; `stroke-dashoffset` shifts where the pattern starts. Set the dash equal to the whole path length and offset it by that same length → the visible dash is pushed entirely off the path (invisible). Animating offset to 0 slides the dash into view, revealing the stroke progressively.
|
||||
|
||||
```
|
||||
visible fraction = 1 - (dashoffset / pathLength)
|
||||
```
|
||||
|
||||
So offset = length → 0% drawn; offset = 0 → 100% drawn; offset = length/2 → 50% drawn (useful for scroll mapping: `offset = length * (1 - progress)`).
|
||||
|
||||
### getTotalLength gotchas
|
||||
|
||||
```js
|
||||
const path = document.querySelector("#sig");
|
||||
const len = path.getTotalLength(); // returns user units of the path geometry
|
||||
path.style.strokeDasharray = len;
|
||||
path.style.strokeDashoffset = len;
|
||||
requestAnimationFrame(() => { // next frame so the transition has a start value
|
||||
path.style.transition = "stroke-dashoffset 1.6s ease";
|
||||
path.style.strokeDashoffset = "0";
|
||||
});
|
||||
```
|
||||
|
||||
- `getTotalLength()` measures the path's own coordinate system, ignoring CSS transforms/scaling — which is what you want for dasharray.
|
||||
- It only works on geometry elements (`path, line, polyline, polygon, circle, ellipse, rect`). For `<text>` draw-on you must convert text to paths first.
|
||||
- Rounding: browsers can clip the last sub-pixel; pad slightly (`len + 1`) if the end never fully closes.
|
||||
- Compound paths (multiple `M` subpaths in one `d`) draw all subpaths simultaneously. Split into separate `<path>`s with staggered `animation-delay` for sequential drawing.
|
||||
|
||||
### No-JS normalization with pathLength
|
||||
|
||||
`pathLength="1"` tells the browser to treat the path's length as exactly 1, regardless of real geometry. Then dash math is unit-free:
|
||||
|
||||
```svg
|
||||
<path d="..." pathLength="1" fill="none" stroke="#111"
|
||||
style="stroke-dasharray:1; stroke-dashoffset:1; animation:draw 1.4s ease forwards"/>
|
||||
```
|
||||
```css
|
||||
@keyframes draw { to { stroke-dashoffset: 0; } }
|
||||
```
|
||||
|
||||
This is the cleanest pure-CSS draw-on and avoids hardcoding measured lengths that break when the path is edited. Use `pathLength="100"` if you prefer to think in percentages.
|
||||
|
||||
### Scroll-driven draw-on (no library, via offset)
|
||||
|
||||
```js
|
||||
const len = path.getTotalLength();
|
||||
path.style.strokeDasharray = len;
|
||||
function onScroll() {
|
||||
const p = Math.min(1, Math.max(0, scrollProgress())); // 0..1
|
||||
path.style.strokeDashoffset = len * (1 - p);
|
||||
}
|
||||
document.addEventListener("scroll", onScroll, { passive: true });
|
||||
```
|
||||
|
||||
## 2. Morphing
|
||||
|
||||
### Why naive morphs break
|
||||
|
||||
Path interpolation walks the `d` command list of A and B in lockstep. If A has 4 cubic curves and B has 7, or A uses `L` where B uses `C`, the browser/animator either refuses or produces garbage. Fixes: match commands by hand, or use a library that resamples.
|
||||
|
||||
### GSAP MorphSVG (best for arbitrary shapes)
|
||||
|
||||
```js
|
||||
import gsap from "gsap";
|
||||
import { MorphSVGPlugin } from "gsap/MorphSVGPlugin";
|
||||
gsap.registerPlugin(MorphSVGPlugin);
|
||||
|
||||
// any shape -> path so it can morph
|
||||
MorphSVGPlugin.convertToPath("#circ, #star");
|
||||
|
||||
gsap.to("#circ", {
|
||||
duration: 0.9, ease: "power2.inOut",
|
||||
morphSVG: { shape: "#star", shapeIndex: "auto", type: "rotational" },
|
||||
});
|
||||
```
|
||||
|
||||
- `shapeIndex` rotates the starting point mapping to minimize twisting; `"auto"` lets GSAP pick, or pass a number to tune.
|
||||
- `type: "rotational"` interpolates angles/lengths instead of raw coordinates — usually smoother for organic morphs.
|
||||
- `map: "size" | "position" | "complexity"` changes how sub-paths in compound shapes are matched.
|
||||
|
||||
### Flubber (standalone, framework-friendly)
|
||||
|
||||
```js
|
||||
import { interpolate, separate, combine } from "flubber";
|
||||
|
||||
// 1 -> 1 shape
|
||||
const lerp = interpolate(pathA, pathB, { maxSegmentLength: 2 });
|
||||
|
||||
// splitting one shape into many (or vice versa)
|
||||
const split = separate(oneShape, [shape1, shape2, shape3], { single: true });
|
||||
```
|
||||
|
||||
Drive `lerp(t)` with any tween/`requestAnimationFrame`, or inside Framer Motion:
|
||||
|
||||
```jsx
|
||||
import { motion, useMotionValue, useTransform, animate } from "motion/react";
|
||||
const progress = useMotionValue(0);
|
||||
const d = useTransform(progress, [0, 1], [0, 1], { clamp: false });
|
||||
const path = useTransform(d, (v) => interpolate(A, B)(v));
|
||||
// animate(progress, 1, { duration: 0.6 }) then <motion.path d={path} />
|
||||
```
|
||||
|
||||
Use Flubber when you can't add GSAP or need React-native value plumbing; use MorphSVG for the highest-quality mapping and convenience.
|
||||
|
||||
### Hand-authored icon toggle (hamburger ↔ close) — no morph library
|
||||
|
||||
When you control both shapes, give them identical structure and animate transforms instead of `d`:
|
||||
|
||||
```svg
|
||||
<svg viewBox="0 0 24 24" class="menu" aria-label="Menu">
|
||||
<line class="top" x1="3" y1="6" x2="21" y2="6"/>
|
||||
<line class="mid" x1="3" y1="12" x2="21" y2="12"/>
|
||||
<line class="bot" x1="3" y1="18" x2="21" y2="18"/>
|
||||
</svg>
|
||||
```
|
||||
```css
|
||||
.menu line { stroke:#111; stroke-width:2; transition: transform .25s ease, opacity .2s ease;
|
||||
transform-origin: center; transform-box: fill-box; }
|
||||
.menu.open .top { transform: translateY(6px) rotate(45deg); }
|
||||
.menu.open .mid { opacity: 0; }
|
||||
.menu.open .bot { transform: translateY(-6px) rotate(-45deg); }
|
||||
```
|
||||
|
||||
`transform-box: fill-box` makes `transform-origin: center` resolve to the element's own bounding box — essential for SVG rotation; without it the origin is the SVG viewport origin.
|
||||
|
||||
## 3. Motion along a path — details
|
||||
|
||||
### GSAP MotionPath
|
||||
|
||||
```js
|
||||
gsap.to("#dot", {
|
||||
duration: 5, repeat: -1, ease: "none",
|
||||
motionPath: {
|
||||
path: "#route",
|
||||
align: "#route", // coordinates relative to the path element
|
||||
alignOrigin: [0.5, 0.5], // pin the object's center to the path
|
||||
autoRotate: true, // or a number to add a constant offset angle
|
||||
start: 0, end: 1, // animate a sub-segment, e.g. 0.2..0.8
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Convert a series of points into a smooth path: `MotionPathPlugin.convertToPath(...)`, or pass `motionPath: [{x:0,y:0},{x:100,y:50},...]` and GSAP draws a curve through them.
|
||||
|
||||
### CSS offset-path (declarative, modern)
|
||||
|
||||
```css
|
||||
.dot {
|
||||
offset-path: path("M10,80 C40,10 120,10 150,80");
|
||||
offset-rotate: auto; /* face direction of travel */
|
||||
animation: travel 3s linear infinite;
|
||||
}
|
||||
@keyframes travel { to { offset-distance: 100%; } }
|
||||
```
|
||||
|
||||
Newer syntax also accepts `offset-path: url(#route)` referencing a `<path>` id and shapes like `ray()`. Good support in evergreen browsers; no JS needed.
|
||||
|
||||
### SMIL animateMotion
|
||||
|
||||
Self-contained inside the SVG; use `rotate="auto"` and `<mpath href="#id"/>`. Best for portable icon assets where you don't want external CSS/JS. Avoid when you need scroll-sync or broad legacy support.
|
||||
|
||||
## 4. SMIL vs CSS vs JS — tradeoffs
|
||||
|
||||
| Axis | SMIL | CSS | JS (GSAP/WAAPI) |
|
||||
|------|------|-----|-----------------|
|
||||
| Bundle cost | none (inline) | none | library (GSAP ~JS) |
|
||||
| Works in `<img>` SVG | yes | yes (internal) | no |
|
||||
| Reach (legacy IE/Edge) | no | partial | yes |
|
||||
| Scroll/scrub sync | hard | hard | easy |
|
||||
| Morph mismatched paths | no | no | yes (MorphSVG/Flubber) |
|
||||
| Timeline orchestration | limited | limited | full |
|
||||
| Animate `d`/gradients/filters | yes | partial | yes |
|
||||
|
||||
Default: CSS for simple declarative effects, GSAP for anything coordinated/scrubbable/morphing, SMIL only for portable self-animating assets in evergreen targets.
|
||||
|
||||
## 5. SVGO config tuned for animation
|
||||
|
||||
Aggressive SVGO defaults will strip the very things you animate. Use a config like:
|
||||
|
||||
```js
|
||||
// svgo.config.js
|
||||
module.exports = {
|
||||
multipass: true,
|
||||
plugins: [
|
||||
{ name: "preset-default", params: { overrides: {
|
||||
removeViewBox: false, // keep responsive scaling
|
||||
cleanupIds: false, // DO NOT rename ids referenced by CSS/JS/SMIL/gradients
|
||||
mergePaths: false, // keep sub-paths separate for staggered draw-on
|
||||
convertShapeToPath: false, // keep <circle>/<rect> if SMIL/CSS targets them
|
||||
removeHiddenElems: false, // keep elements you toggle visible via animation
|
||||
inlineStyles: false, // preserve class hooks
|
||||
} } },
|
||||
{ name: "removeDimensions" }, // drop width/height, keep viewBox -> fluid scaling
|
||||
{ name: "prefixIds" }, // namespace ids if inlining many SVGs to avoid id collisions
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
If multiple inlined SVGs share gradient/filter ids, id collisions make the LAST definition win for everyone — `prefixIds` (or unique authoring) prevents this classic bug.
|
||||
|
||||
## 6. Reduced motion
|
||||
|
||||
```css
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.path { animation: none; stroke-dashoffset: 0; } /* show final drawn state instantly */
|
||||
}
|
||||
```
|
||||
|
||||
For looping decorative SVG (spinners, ambient gradients), pause or hide them under reduced-motion; for functional icon toggles, keep the state change but drop the easing duration.
|
||||
|
||||
---
|
||||
Pick the right method per shape and SVG draws, morphs, and travels smoothly. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=svg-animation)** — the AI motion agent for editable, on-brand motion graphics.
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/60fps-animation
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/accessible-animation
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/ascii-animation
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/glassmorphism
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/gsap-web
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/lottie-animation
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/micro-interaction
|
||||
@@ -0,0 +1 @@
|
||||
../../.agents/skills/page-transition-animation
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/svg-animation
|
||||
@@ -0,0 +1,59 @@
|
||||
{
|
||||
"version": 1,
|
||||
"skills": {
|
||||
"60fps-animation": {
|
||||
"source": "iart-ai/web-animation-skills",
|
||||
"sourceType": "github",
|
||||
"skillPath": "skills/60fps-animation/SKILL.md",
|
||||
"computedHash": "d832ea4a0dc07c18483d4fd39352c65e4daa2f298998290730cf159df30f400e"
|
||||
},
|
||||
"accessible-animation": {
|
||||
"source": "iart-ai/web-animation-skills",
|
||||
"sourceType": "github",
|
||||
"skillPath": "skills/accessible-animation/SKILL.md",
|
||||
"computedHash": "46695e422851b64f2b680924584ba9f7690309c109b6d98925ef3021b139167c"
|
||||
},
|
||||
"ascii-animation": {
|
||||
"source": "iart-ai/web-animation-skills",
|
||||
"sourceType": "github",
|
||||
"skillPath": "skills/ascii-animation/SKILL.md",
|
||||
"computedHash": "cc219b1851f713f76934a2738ccdcec37d4a266f1d20ecc346487290cc40d2fb"
|
||||
},
|
||||
"glassmorphism": {
|
||||
"source": "iart-ai/web-animation-skills",
|
||||
"sourceType": "github",
|
||||
"skillPath": "skills/glassmorphism/SKILL.md",
|
||||
"computedHash": "c98e77044561fea5e51116156d0ba600a56f9961ed18b498d72504d49aff7882"
|
||||
},
|
||||
"gsap-web": {
|
||||
"source": "iart-ai/web-animation-skills",
|
||||
"sourceType": "github",
|
||||
"skillPath": "skills/gsap-web/SKILL.md",
|
||||
"computedHash": "11585ce3142acae8db34c9d0eb57e03834972f1095643266eb2c41b432564b1d"
|
||||
},
|
||||
"lottie-animation": {
|
||||
"source": "iart-ai/web-animation-skills",
|
||||
"sourceType": "github",
|
||||
"skillPath": "skills/lottie-animation/SKILL.md",
|
||||
"computedHash": "3b9838145f5af19d03014a5eca9041ae0ba267b77e312332a129f3fe40078f68"
|
||||
},
|
||||
"micro-interaction": {
|
||||
"source": "iart-ai/web-animation-skills",
|
||||
"sourceType": "github",
|
||||
"skillPath": "skills/micro-interaction/SKILL.md",
|
||||
"computedHash": "f236bc97a9f4c0e9c9a045d0b591e3ca6b6b2aeb26e42b661c15211f652ac131"
|
||||
},
|
||||
"page-transition-animation": {
|
||||
"source": "iart-ai/web-animation-skills",
|
||||
"sourceType": "github",
|
||||
"skillPath": "skills/page-transition-animation/SKILL.md",
|
||||
"computedHash": "62e103e2313433e77db26c67fdcae1c425030e1a51d0f5ffc0fb6fdac6d36132"
|
||||
},
|
||||
"svg-animation": {
|
||||
"source": "iart-ai/web-animation-skills",
|
||||
"sourceType": "github",
|
||||
"skillPath": "skills/svg-animation/SKILL.md",
|
||||
"computedHash": "b6902577f093a1cd724052b94e633154cb42020b5001138185982fb4ce230404"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user