# javascript-animation

Adopt this skill: https://proskills.md/skills/other/iart-ai-javascript-animation-skills-skills-javascript-animation

Page: https://proskills.md/skills/other/iart-ai-javascript-animation-skills-skills-javascript-animation
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: skills/javascript-animation/SKILL.md
size: 9088
sha: 9187ecaf0f295f2225a342d30b1903e42050dde8
upstream: https://github.com/iart-ai/javascript-animation-skills/blob/main/skills/javascript-animation/SKILL.md

````text
---
name: javascript-animation
description: This skill should be used when the user asks to "draw every frame in JavaScript", "make an animation with no image assets", "animate this in code / on a canvas", "make a hand-drawn style animated video", "turn this into a short animated film", "make an animated explainer drawn in code", "make an animated story / picture book of my photos", or "make a zero-asset animation like the Opus 5.5 ones". Produces a single self-contained HTML file whose frames are computed on an HTML canvas (seekable, deterministic), renders it to MP4, and self-checks the result. Pairs with the soundtrack skill for code-synthesized music. NOT for charts from data (use chart-animation) or 3D/WebGL (use threejs-animation / shader-glsl from webgl-animation-skills); pure text motion and depth drawn by projection on the 2D canvas are in scope.
version: 0.4.1
---

# JavaScript Animation (every frame drawn in code)

Make short animated films where every pixel is computed: no images, no fonts to load, no libraries. One HTML file holds the whole piece; a headless browser seeks it frame by frame into an MP4.

## Model

Built and tested with Claude Opus 5.5; drawing quality depends heavily on the model. The self-check below needs image input: if the current model can't see images, say so to the user and treat visual verification as not done. Other models are untested; if the result looks crude, say that a stronger model is likely to help rather than claim it's the best possible.

## Default flow: don't stop to ask

Run straight through. Pick sensible defaults and mention alternatives at delivery. Ask *before* starting only if there is no subject at all (e.g. "make an animation", nothing else).

1. **Read the brief.** Infer the form (story, explainer, poem, loop, interactive page), length (default 15-20 s; longer only when the subject cannot be told in that time) and aspect (default 1920x1080) from what the user said. On-screen text is in the language the user wrote the brief in; make it bilingual only if they ask or the audience clearly is. `references/forms.md` has a short structure for each form.
2. **Plan the look and sound from the subject and the audience,** in your own words: what the film is, how it looks and sounds, and why that fits this subject and this audience. There is no list to fill in; `references/techniques.md` has ingredients, and the starter's values are placeholders, not a house style. Never reuse the look or sound of a previous piece by default: two different subjects should not come out looking or sounding alike. If the user points at someone else's piece ("like that viral one"), borrow its techniques, never its characters, story or compositions.
3. **Beat grid, storyboard and blocking, as data** (`references/storyboard.md`). Tempo and sections first; then a shot list with a pace that fits the form (pace table in `references/storyboard.md`; each shot with framing, camera move, action, the beat it lands on, its sound, its transition); then the blocking (for a story or an explainer, the tracks of one continuous world). These go into the page as `BPM`, `SECTIONS`, `SHOTS`, `EVENTS`: the scenes, camera and soundtrack all read them, so picture and sound line up by construction. For a story or an explainer, check the logic: every beat caused by the one before, the metaphor visible in the picture.
4. **Build from `templates/starter.html`.** It is already storyboard-driven: one world drawn in world coordinates, `withCamera` per shot, `claim()` for every piece of text and every key object. Replace the placeholder palette and the demo world. Keep the contract: `draw(frame)` is a pure function of the frame number. Use `rng(seed)` / `hash2()`, never `Math.random` or `Date`.
5. **Self-check, then render** (next section). Fix and re-check until clean.
6. **Deliver:** the MP4 and the HTML (it plays live in a browser; clicking starts the sound). Then, in one or two lines, offer what can change: another look, AI music instead of synthesized, different length.

For music, use the `soundtrack` skill (default: synthesized in the page with Web Audio, no key needed).

## Self-check (the agent does this; the user never sees it)

```bash
node scripts/render.mjs piece.html sheet.jpg --sheet 1        # one frame per second, stepping off cuts
node scripts/render.mjs piece.html shot --stills 90,300,610   # specific moments
node scripts/render.mjs piece.html piece.mp4                  # full render (+ soundtrack if the page has one)
node scripts/asset-audit.mjs piece.html                       # proves zero-asset: exit 1 if anything is loaded or embedded
node scripts/layout-check.mjs piece.html                      # text colliding with text, or straddling a claimed object
node ../soundtrack/scripts/sync-check.mjs piece.mp4 --cues-file piece.cues.json   # cuts on the beat, no startle
```

Then two passes by eye, both in `references/qc.md`:
1. **Storyboard conformance**: a still at the action beat of every shot, read against its row (is the actor where the blocking says, doing what the row says?).
2. **Director pass**: the contact sheet at 2 frames per second (`--sheet .5`), scored for pace against the form, framing variety, dead frames, whether every action has its sound, and whether the look fits the audience. Do at least two rounds.
Render stills of the frames you change instead of re-rendering the whole film each time.

## Only if triggered

| When | Do |
|---|---|
| A character appears in more than one scene | Before the scenes, render the character alone (expressions + poses) and check it yourself against `references/character.md`. Characters expose anchor points (mouth, hands) so props attach to them. |
| The user supplied photos of real people, pets or places | Build the character from the photos with the extraction method in `references/character.md`. Photos stay local: never upload them or put them in anything published. |
| It's a real-person piece and the user is present | At delivery (not before), offer to use photos of key props or people to make it more theirs. |
| Text or a speech bubble follows a moving character | Place it with `placeFree(w, h, [above, right, left, below])` so it steps aside from anything already claimed. |
| On-screen text is not Latin (Chinese, Japanese...) | Use a CJK font stack; check every glyph renders (monospace fonts silently swap missing glyphs, e.g. `≈` became `=`). |
| The page will be published as a web page | Deliver the HTML; keep the live preview loop and the click-to-play audio. |

## Rules that prevent the common failures

- **Pure function of time.** No `requestAnimationFrame` state, no CSS animations, no accumulated physics: compute each frame from `t` alone, or the render and the preview disagree.
- **A hand-drawn line boils, it doesn't jitter.** When a film sets `LOOK.wobble`, change the wobble seed every 4 frames (`LOOK.boil: 4`), not every frame. Every frame reads as noise; ~7.5 changes a second reads as hand-drawn.
- **Rounded forms for bodies.** Build figures from ellipses and rounded rectangles. Raw polygons with few points read as signs (a pentagon hand, a box torso).
- **Pick the angle that makes the pose read.** A long body with stubby limbs from the side reads as a caterpillar; the same pose from the front (foreshortened) reads as a baby on its tummy.
- **Draw back to front, explicitly.** Back hair, then body, then neck, then face, then front hair. Most "something covers the face" bugs are draw order.
- **Hit points on cuts and actions.** Every cut and every visible action is in `EVENTS`/`CUES`; the soundtrack lands on them (see `soundtrack`).
- **Text never collides.** Claim every text box and key object; `layout-check` must print CLEAN. A caption overlapping a monitor edge or a face looks careless, and eyes on a contact sheet miss it.

## Files

- `templates/starter.html`: drawing library (ink, illustration, flat/blueprint primitives, labels, paper, filtered layers), `withCamera`, `claim`/`placeFree`, and a storyboard-driven two-shot skeleton.
- `scripts/render.mjs`: MP4 / stills / contact sheet. `window.CUES` and `window.SCORE` are optional: on a full render it writes `<out>.cues.json` and muxes the SCORE soundtrack (no SCORE = silent MP4). Needs an even canvas size.
- `scripts/asset-audit.mjs`: static scan + live network check for anything loaded or embedded.
- `scripts/layout-check.mjs`: reads `window.LAYOUT` over the whole film and lists text collisions with their times.
- `references/storyboard.md`: beat grid, shot list, blocking, continuity and story logic.
- `references/techniques.md`: tested drawing techniques (ink, spot-color print, single-line engraving, words as shapes, marker fills, illustration shapes).
- `references/forms.md`: structure notes per form.
- `references/character.md`: only when there's a character.
- `references/qc.md`: the self-check list.

Requirements: Node 18+, ffmpeg, Chrome (or `npx playwright install chromium`), and `npm i playwright-core` in the folder you run the scripts from (your project, not the skill folder).
````

## File: skills/javascript-animation/scripts/asset-audit.mjs
size: 3273
sha: 8d6a4748cb5fd0e51a12deedb885d5c445541b01
upstream: https://github.com/iart-ai/javascript-animation-skills/blob/main/skills/javascript-animation/scripts/asset-audit.mjs

```text
#!/usr/bin/env node
// asset-audit.mjs: prove a page is zero-asset (every pixel computed, nothing loaded).
// Static scan of the HTML for anything that pulls in images, video, audio, fonts, scripts or data,
// then a live check: load the page and record every network request it makes.
//
// usage: node asset-audit.mjs page.html     exit 0 = clean, 1 = something is loaded or embedded
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { createRequire } from 'node:module';
// resolve playwright from the skill folder, else from the project you run it in (where you `npm i playwright-core`)
async function loadChromium() {
  for (const name of ['playwright-core', 'playwright']) {
    try { return (await import(name)).chromium; } catch {}
    try { return createRequire(process.cwd() + '/')(name).chromium; } catch {}
  }
  throw new Error('playwright-core not found: run `npm i playwright-core` in this folder');
}

const file = process.argv[2];
if (!file) { console.error('usage: node asset-audit.mjs page.html'); process.exit(1); }
const src = readFileSync(file, 'utf8');

const RULES = [
  [/<img\b/gi, '<img> tag'],
  [/<(video|audio|source|picture|object|embed|iframe)\b/gi, 'media / embed tag'],
  [/<link\b[^>]*rel=["']?(stylesheet|preload|icon)/gi, '<link> to an external resource'],
  [/<script\b[^>]*\bsrc=/gi, 'external <script src>'],
  [/data:(image|audio|video|font|application)\//gi, 'embedded data: URI'],
  [/url\(\s*['"]?(?!#)[^)'"\s]+/gi, 'CSS url(...)'],
  [/@import\b/gi, 'CSS @import'],
  [/@font-face\b/gi, '@font-face (loaded font)'],
  [/\b(fetch|XMLHttpRequest|importScripts)\s*\(/g, 'network call'],
  [/\bnew\s+(Image|Audio|FontFace)\s*\(/g, 'new Image/Audio/FontFace'],
  [/\bimport\s*\(\s*['"]/g, 'dynamic import'],
  [/['"][^'"\s]+\.(png|jpe?g|gif|webp|avif|svg|mp4|webm|mov|mp3|wav|ogg|m4a|woff2?|ttf|otf|json)['"]/gi, 'file reference'],
  [/[A-Za-z0-9+/]{400,}={0,2}/g, 'long base64-like blob'],
];
const lineOf = i => src.slice(0, i).split('\n').length;
const hits = [];
for (const [re, what] of RULES) for (const m of src.matchAll(re)) hits.push({ line: lineOf(m.index), what, text: m[0].slice(0, 60) });

// live check: any request other than the page itself means something is loaded
let requests = [];
try {
  const chromium = await loadChromium();
  let browser; try { browser = await chromium.launch({ channel: 'chrome' }); } catch { browser = await chromium.launch(); }
  const page = await browser.newPage(), self = 'file://' + resolve(file);
  page.on('request', r => { if (!r.url().startsWith(self)) requests.push(r.url()); });
  await page.goto(self + '?render'); await page.waitForTimeout(1500);
  await browser.close();
} catch (e) { console.warn('live check skipped (playwright-core not available):', e.message); }

const kb = (Buffer.byteLength(src) / 1024).toFixed(0);
if (!hits.length && !requests.length) {
  console.log(`CLEAN: ${file} (${kb} KB) embeds and loads nothing; every frame is computed in code.`);
} else {
  for (const h of hits) console.log(`line ${h.line}: ${h.what}: ${h.text}`);
  for (const r of requests) console.log(`network request: ${r}`);
  console.log(`\nNOT zero-asset: ${hits.length} static hit(s), ${requests.length} request(s).`);
  process.exitCode = 1;
}
```

## File: skills/javascript-animation/scripts/layout-check.mjs
size: 3848
sha: 522ebacdf1023df0f9c8627ef143674d490ca4df
upstream: https://github.com/iart-ai/javascript-animation-skills/blob/main/skills/javascript-animation/scripts/layout-check.mjs

```text
#!/usr/bin/env node
// layout-check.mjs: find text that collides with other text or straddles a key object.
//
// The page registers boxes while it draws each frame and exposes them as window.LAYOUT:
//   [{ id: 'chat bubble', kind: 'text' | 'keep', x, y, w, h }, ...]   (screen pixels)
// `claim(id, kind, x, y, w, h)` in the starter does this from the current transform.
// Flags, per sampled frame:
//   text vs text overlapping at all
//   text vs keep overlapping partially (text fully inside a keep, e.g. a caption on a screen, is fine)
// usage: node layout-check.mjs page.html [--every 0.1] [--min 4]      exit 1 if anything collides
import { resolve } from 'node:path';
import { createRequire } from 'node:module';
async function loadChromium() {
  for (const name of ['playwright-core', 'playwright']) {
    try { return (await import(name)).chromium; } catch {}
    try { return createRequire(process.cwd() + '/')(name).chromium; } catch {}
  }
  throw new Error('playwright-core not found: run `npm i playwright-core` in this folder');
}
const args = process.argv.slice(2), file = args[0];
const opt = (n, d) => { const i = args.indexOf(n); return i < 0 ? d : Number(args[i + 1]); };
if (!file) { console.error('usage: node layout-check.mjs page.html [--every 0.1] [--min 4]'); process.exit(1); }
const EVERY = opt('--every', .1), MIN = opt('--min', 4);          // ignore overlaps thinner than MIN px

const chromium = await loadChromium();
let browser; try { browser = await chromium.launch({ channel: 'chrome' }); } catch { browser = await chromium.launch(); }
const page = await browser.newPage();
await page.goto('file://' + resolve(file) + '?render');
const { FRAMES, FPS } = await page.evaluate(() => ({ FRAMES: window.FRAMES, FPS: window.FPS }));
const frames = []; for (let t = 0; t * FPS < FRAMES; t += EVERY) frames.push(Math.round(t * FPS));
const layouts = await page.evaluate(fs => fs.map(f => { window.draw(f); return window.LAYOUT || null; }), frames);
await browser.close();
if (layouts.every(l => l === null)) { console.error('the page exposes no window.LAYOUT: call claim(...) for text and key objects while drawing'); process.exit(1); }

const inter = (a, b) => [Math.max(0, Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x)), Math.max(0, Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y))];
const inside = (a, b) => a.x >= b.x - 1 && a.y >= b.y - 1 && a.x + a.w <= b.x + b.w + 1 && a.y + a.h <= b.y + b.h + 1;
const onScreen = a => a.x + a.w > 0 && a.y + a.h > 0 && a.x < 1e5 && a.w > 0 && a.h > 0;
const hits = new Map();                                              // "a × b" -> [times]
layouts.forEach((L, i) => {
  if (!L) return; const boxes = L.filter(onScreen);
  for (let p = 0; p < boxes.length; p++) for (let q = p + 1; q < boxes.length; q++) {
    const a = boxes[p], b = boxes[q]; if (a.kind !== 'text' && b.kind !== 'text') continue;
    const [ox, oy] = inter(a, b); if (ox < MIN || oy < MIN) continue;
    if (a.kind === 'text' && b.kind === 'keep' && inside(a, b)) continue;
    if (b.kind === 'text' && a.kind === 'keep' && inside(b, a)) continue;
    const key = `${a.id} × ${b.id}`; if (!hits.has(key)) hits.set(key, []); hits.get(key).push(frames[i] / FPS);
  }
});
if (!hits.size) { console.log(`CLEAN: no text collisions in ${frames.length} sampled frames (every ${EVERY}s).`); process.exit(0); }
const spans = ts => { const out = []; for (const t of ts) { const last = out[out.length - 1]; if (last && t - last[1] <= EVERY * 1.5) last[1] = t; else out.push([t, t]); } return out.map(([a, b]) => a === b ? `${a.toFixed(1)}s` : `${a.toFixed(1)}-${b.toFixed(1)}s`).join(', '); };
for (const [k, ts] of hits) console.log(`${k}: ${spans(ts)}`);
console.log(`\n${hits.size} collision(s). Move, resize or time-shift the text; render stills at those times to confirm.`);
process.exitCode = 1;
```

## File: skills/javascript-animation/scripts/render.mjs
size: 9083
sha: 7d9bdc4a48671bfffcb3ef987d82699c8af7c023
upstream: https://github.com/iart-ai/javascript-animation-skills/blob/main/skills/javascript-animation/scripts/render.mjs

```text
#!/usr/bin/env node
// render.mjs: seek-render a canvas animation page to MP4, stills, or a contact sheet.
//
// The page must expose:  window.draw(frame)  window.FRAMES  window.FPS
// and optionally:        window.CUES = [seconds, ...]   (scene cuts / hit points for the soundtrack)
//                        window.SCORE = ac => {...}     (Web Audio soundtrack; rendered offline and muxed in)
// It is loaded with ?render so it can skip its own preview loop.
//
// Usage:
//   node render.mjs page.html out.mp4                  full render (H.264, yuv420p)
//   node render.mjs page.html shot --stills 0,150,300  -> shot-0000.jpg shot-0150.jpg ...  (frames; or seconds: 2.5s,7s)
//   node render.mjs page.html sheet.jpg --sheet [1]    one frame every N seconds, tiled into one image
// Both are optional. On a full render, CUES are written to <out>.cues.json, and SCORE is rendered
// offline to <out>.wav and muxed into the MP4 (without SCORE the MP4 is silent).
// A full render needs an even canvas size (H.264); an output with no extension gets .mp4.
//
// Needs: node >= 18, `npm i playwright-core`, ffmpeg, and Chrome installed
// (or run `npx playwright install chromium` once).
import { createRequire } from 'node:module';
import { spawn, execFileSync } from 'node:child_process';
import { writeFileSync, mkdtempSync, rmSync, renameSync } from 'node:fs';
import { resolve, join, parse, format } from 'node:path';
import { tmpdir } from 'node:os';

// resolve playwright from the skill folder, else from the project you run it in (where you `npm i playwright-core`)
async function loadChromium() {
  for (const name of ['playwright-core', 'playwright']) {
    try { return (await import(name)).chromium; } catch {}
    try { return createRequire(process.cwd() + '/')(name).chromium; } catch {}
  }
  throw new Error('playwright-core not found: run `npm i playwright-core` in this folder');
}
const chromium = await loadChromium();

const args = process.argv.slice(2);
const [pagePath, outArg] = args;
const opt = name => { const i = args.indexOf(name); return i < 0 ? undefined : (args[i + 1] && !args[i + 1].startsWith('--') ? args[i + 1] : true); };
if (!pagePath || !outArg) { console.error('usage: node render.mjs page.html <out> [--stills f1,f2] [--sheet [seconds]]'); process.exit(1); }

let browser;
try { browser = await chromium.launch({ channel: 'chrome' }); } catch { browser = await chromium.launch(); }
const page = await browser.newPage();
const errors = [];
page.on('pageerror', e => errors.push(e.message));
await page.goto('file://' + resolve(pagePath) + '?render');
const info = await page.evaluate(() => {
  const c = document.querySelector('canvas');
  return { FRAMES: window.FRAMES, FPS: window.FPS, CUES: window.CUES, w: c?.width, h: c?.height, hasDraw: typeof window.draw === 'function', hasScore: typeof window.SCORE === 'function' };
});
if (!info.hasDraw || !info.FRAMES || !info.FPS) { console.error('page must define window.draw(frame), window.FRAMES and window.FPS', errors); process.exit(1); }
const stillsOrSheet = opt('--stills') || opt('--sheet');
if (!stillsOrSheet && (info.w % 2 || info.h % 2)) { console.error(`canvas is ${info.w}x${info.h}: H.264 needs even width and height; change the <canvas> size`); await browser.close(); process.exit(1); }
// a full render with no extension becomes .mp4; sidecars (.cues.json, .wav) sit next to the output
const out = !stillsOrSheet && !parse(outArg).ext ? outArg + '.mp4' : outArg;
const sidecar = ext => { const p = parse(out); return format({ dir: p.dir, name: p.ext ? p.name : p.base, ext }); };

const grab = f => page.evaluate(f => { window.draw(f); return document.querySelector('canvas').toDataURL('image/jpeg', 0.93).split(',')[1]; }, f);
const jpg = async f => Buffer.from(await grab(f), 'base64');
// for contact sheets: stamp the timestamp in the browser (ffmpeg drawtext is missing from many builds)
const stamped = async (f, fps) => Buffer.from(await page.evaluate(([f, fps]) => {
  window.draw(f); const src = document.querySelector('canvas'), c = document.createElement('canvas');
  c.width = src.width; c.height = src.height; const x = c.getContext('2d'); x.drawImage(src, 0, 0);
  const s = Math.round(src.width / 16); x.fillStyle = 'rgba(0,0,0,.65)'; x.fillRect(0, 0, s * 3.1, s * 1.3);
  x.fillStyle = '#fff'; x.font = `700 ${Math.round(s * .8)}px monospace`; x.textBaseline = 'middle'; x.fillText((f / fps).toFixed(2) + 's', s * .25, s * .66);
  return c.toDataURL('image/jpeg', .9).split(',')[1];
}, [f, fps]), 'base64');

if (opt('--stills')) {
  for (const f of String(opt('--stills')).split(',').map(v => v.trim().endsWith('s') ? Math.round(parseFloat(v) * info.FPS) : Number(v))) {
    const file = `${out}-${String(f).padStart(4, '0')}.jpg`; writeFileSync(file, await jpg(f)); console.log(file);
  }
} else if (opt('--sheet')) {
  const every = opt('--sheet') === true ? 1 : Number(opt('--sheet'));
  // sample every N seconds, but step off scene cuts: a frame inside the dip-to-paper looks blank
  const near = t => (info.CUES || []).find(c => Math.abs(t - c) < .35);
  // start half a step in: frame 0 is often an empty fade-in, and cuts tend to sit on whole seconds
  const frames = []; for (let t = every / 2; t * info.FPS < info.FRAMES; t += every) { const c = near(t); frames.push(Math.min(info.FRAMES - 1, Math.round((c !== undefined ? c + .45 : t) * info.FPS))); }
  const dir = mkdtempSync(join(tmpdir(), 'sheet-'));
  for (let i = 0; i < frames.length; i++) writeFileSync(join(dir, `f${String(i).padStart(4, '0')}.jpg`), await stamped(frames[i], info.FPS));
  const cols = Math.ceil(Math.sqrt(frames.length)), rows = Math.ceil(frames.length / cols), tw = 360;
  execFileSync('ffmpeg', ['-y', '-loglevel', 'error', '-i', join(dir, 'f%04d.jpg'),
    '-vf', `scale=${tw}:-2,tile=${cols}x${rows}`,
    '-frames:v', '1', out]);
  rmSync(dir, { recursive: true });
  console.log(`contact sheet: ${frames.length} frames (every ${every}s) -> ${out}`);
} else {
  const ff = spawn('ffmpeg', ['-y', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(info.FPS), '-c:v', 'mjpeg', '-i', '-',
    '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-crf', '18', '-movflags', '+faststart', out], { stdio: ['pipe', 'inherit', 'inherit'] });
  let ffDone = false, ffCode = null; const closed = new Promise(r => ff.on('close', c => { ffDone = true; ffCode = c; r(); }));
  ff.on('error', e => { console.error('ffmpeg failed to start:', e.message); process.exit(1); });
  ff.stdin.on('error', () => {}); // reported below via the exit code
  for (let f = 0; f < info.FRAMES; f++) {
    if (ffDone) break;
    if (!ff.stdin.write(await jpg(f))) await Promise.race([new Promise(r => ff.stdin.once('drain', r)), closed]);
    if (f % (info.FPS * 5) === 0) console.log(`frame ${f}/${info.FRAMES}`);
  }
  ff.stdin.end();
  await closed;
  if (ffCode !== 0) { console.error(`ffmpeg exited with code ${ffCode}; ${out} is incomplete`); await browser.close(); process.exit(1); }
  console.log(`rendered ${info.FRAMES} frames @ ${info.FPS}fps -> ${out}`);
  if (Array.isArray(info.CUES)) { writeFileSync(sidecar('.cues.json'), JSON.stringify(info.CUES)); console.log(`cues -> ${sidecar('.cues.json')}`); }
  if (info.hasScore) {
    // render the page's Web Audio score offline (deterministic, faster than real time) -> 16-bit WAV
    const wav64 = await page.evaluate(async secs => {
      const SR = 48000, ac = new OfflineAudioContext(2, Math.ceil(SR * secs), SR);
      window.SCORE(ac);
      const buf = await ac.startRendering(), n = buf.length, L = buf.getChannelData(0), R = buf.getChannelData(1);
      let peak = 1e-9; for (let i = 0; i < n; i++) peak = Math.max(peak, Math.abs(L[i]), Math.abs(R[i]));
      const g = .89 / peak, dv = new DataView(new ArrayBuffer(44 + n * 4)), w = (o, s) => [...s].forEach((c, i) => dv.setUint8(o + i, c.charCodeAt(0)));
      w(0, 'RIFF'); dv.setUint32(4, 36 + n * 4, true); w(8, 'WAVEfmt '); dv.setUint32(16, 16, true); dv.setUint16(20, 1, true); dv.setUint16(22, 2, true);
      dv.setUint32(24, SR, true); dv.setUint32(28, SR * 4, true); dv.setUint16(32, 4, true); dv.setUint16(34, 16, true); w(36, 'data'); dv.setUint32(40, n * 4, true);
      for (let i = 0; i < n; i++) { dv.setInt16(44 + i * 4, Math.max(-1, Math.min(1, L[i] * g)) * 32767, true); dv.setInt16(46 + i * 4, Math.max(-1, Math.min(1, R[i] * g)) * 32767, true); }
      const bytes = new Uint8Array(dv.buffer); let bin = ''; for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
      return btoa(bin);
    }, info.FRAMES / info.FPS);
    const wav = sidecar('.wav'), silent = sidecar('.silent.mp4');
    writeFileSync(wav, Buffer.from(wav64, 'base64'));
    renameSync(out, silent);
    execFileSync('ffmpeg', ['-y', '-loglevel', 'error', '-i', silent, '-i', wav, '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-shortest', out]);
    rmSync(silent);
    console.log(`soundtrack (window.SCORE) -> ${wav}, muxed into ${out}`);
  }
}
if (errors.length) console.warn('page errors:', errors);
await browser.close();
```

## File: skills/javascript-animation/references/character.md
size: 2912
sha: d3d08573f4ba49021079f39acd15ac191220451e
upstream: https://github.com/iart-ai/javascript-animation-skills/blob/main/skills/javascript-animation/references/character.md

```text
# Characters (only when one appears in more than one scene)

## Design it once, alone, before the scenes

Render the character by itself in every expression and pose the storyboard needs (e.g. eyes open / asleep / smiling / crying; mouths; the 2-3 poses). Look at that one sheet and fix it there. A character problem found inside the full film costs a whole re-render per attempt; found on the sheet it costs one still.

To render it alone, add a temporary first shot that draws only the character in a grid of expressions and poses, and take a still of it (`--stills 0`); remove the shot afterwards. This is a self-check. Don't stop to ask the user to approve it.

Write the character as one function with options, e.g. `hero(cx, cy, r, { eyes, mouth, lookX, lookY, rot, sway })`, so every scene draws the same person.

## Anchor points

Expose the places props attach to (mouth, hands, feet) as functions of the character's position, size and rotation, e.g. `mouthOf(cx, cy, r, rot)`. Place bottles, cards and toys from those anchors. Hard-coded coordinates drift the moment the character moves, and the bottle ends up nowhere near the mouth.

## From photos to a character (only if the user gave photos)

1. List the 3-5 features that make this person *them*: for a baby it might be hair that sticks straight up, very full cheeks, a particular printed onesie, a tiny fist. Ignore everything else.
2. Exaggerate those features and simplify the rest. A likeness comes from the signature features, not from accuracy.
3. For babies and cute characters: big head, features set low on the face, small widely spaced eyes with a highlight, soft blush. Features high on the face read as older.
4. Pull real colors and objects from the photos: the actual stroller, bathtub, blanket print, room colors. These make the piece feel like *theirs* more than facial accuracy does.
5. Stay clearly stylized. A near-realistic drawing of someone the viewer knows well reads as uncanny; a cartoon doesn't.
6. Photos are for looking at locally. Never upload them, embed them, or put them in anything published.

Grown-ups next to a baby (a family portrait): tell them apart by hair (long, tied, bob, short, buzz), glasses, clothes color and what they hold, rather than facial detail.

## Poses that read

- Pick the camera angle that makes the pose unmistakable. Tummy time from the side is a long blob with stubby arms (it reads as a caterpillar); from the front it's a head, shoulders, two forearms on the mat and feet peeking up behind.
- Every head sits on a neck or shoulders. A gap between head and body reads as a floating head.
- Hands: rounded mitt + thumb, never a polygon.
- Draw back to front: back hair, body, neck, face, front hair, then anything held in front.
- Hair: a few curved, tapering strands of different lengths leaning together read as hair; evenly spaced identical spikes read as a crown or a sea urchin.
```

## File: skills/javascript-animation/references/forms.md
size: 1919
sha: b69c39131f2fcaabfbc2340a33e4714e4447a76d
upstream: https://github.com/iart-ai/javascript-animation-skills/blob/main/skills/javascript-animation/references/forms.md

```text
# Forms

Infer the form from the brief; don't ask unless nothing points anywhere. These are structure notes, not templates: adapt them to the subject.

## Story (a character, something happens)

- 2-5 s per shot, grouped into a few scenes. One beat per shot.
- A title beat (2-4 s), a middle that changes something, an ending that lands and **holds** (let motion stop before the last line appears).
- Wordless works (Kevin Ngo's watermelon piece has no text). If there are captions, keep them short and bilingual only if the audience is.
- A recurring character carries the film: see `character.md`.
- One specific, human detail beats general adjectives (the name on a mug, the one sock that never matches).

## Explainer (make a mechanism clear)

- Open on the question (or a cloud of questions), not the answer.
- One mechanism step per scene, numbered if the audience needs a map.
- Show causality, not labels: things fall, fill, count up, fade away, because of the previous thing. (In the newborn-vision example, photons land on cones and a counter shows how much light each eye catches.)
- An on-screen gauge or counter that persists across scenes turns a sequence into a chain.
- End with a one-line recap of the chain.
- Every fact on screen needs a source you can name. Put the sources next to the piece (e.g. a README).

## Poem / ambient

- No plot; a mood and 2-3 images that transform into each other.
- Slower: 6-10 s per image, long crossfades, very little text.

## Loop

- The last frame must equal the first. Build every motion from `Math.sin(2πt / DUR)` (or anything periodic in DUR) so the seam is invisible.
- Check the seam: render stills of frame 0 and frame FRAMES-1 side by side.

## Interactive page (not a video)

- Same drawing code, but deliver the HTML: keep the preview loop, add hover/click where it helps.
- Still keep `draw(frame)` pure so a preview video can be rendered for sharing.
```

## File: skills/javascript-animation/references/qc.md
size: 3732
sha: e66c09dec1180929579afb7ba6f3dd9ab06fd90c
upstream: https://github.com/iart-ai/javascript-animation-skills/blob/main/skills/javascript-animation/references/qc.md

```text
# Self-check before delivering

Scripts first: `asset-audit` CLEAN, `layout-check` CLEAN, `sync-check` passing (a remaining STARTLE is acceptable only on a deliberate stinger you can name). Then the two passes by eye below.

The agent runs this; the user never sees it. Open the contact sheet (`render.mjs page.html sheet.jpg --sheet 1`; it steps off scene cuts so dip frames don't look like blank ones) and go down the list. Fix, render stills of the changed frames, and check again.

## Frames

- [ ] No blank or near-blank frames except the intended dips at cuts.
- [ ] Every scene reads in one second: can you say what's happening from the thumbnail alone?
- [ ] `layout-check.mjs` prints CLEAN (every text box and key object claimed). Eyes miss these: a "sent" label sitting on a monitor's edge passed two human looks.
- [ ] Text fits its box, doesn't overlap a face or a key object, and every glyph renders (monospace fonts swap missing glyphs silently: `≈` showed up as `=`). Non-Latin text uses a CJK font stack.
- [ ] Labels that type on: the box grows with the text (a full-width box with two letters in it looks broken).

## Shapes and figures

- [ ] Each shape reads as the thing it is. Few-point polygons read as signs (a pentagon hand, a box torso); rebuild them from rounded forms.
- [ ] Silhouettes read: a pose that looks like something else (a baby on its tummy that reads as a caterpillar) needs a different angle, not more detail.
- [ ] Nothing floats: heads sit on necks/shoulders, props touch the hand or mouth that holds them (place props from anchor points).
- [ ] Draw order is right: nothing covers a face; back hair is behind the body.
- [ ] A recurring character looks the same in every scene.

## Storyboard conformance

- [ ] A still at the action beat of every shot matches its storyboard row: actor where the blocking says, doing what the row says, and the cause of the action visible.
- [ ] The gag/metaphor reads without explanation (someone seeing the frame cold understands it). A deliberate misspelling read as our own typo means the picture didn't carry it.

## Staging

- [ ] Objects rest on something (a monitor on a desk with a stand), people have feet on a floor, nothing hovers unless that's the point.
- [ ] Figures are distinct from the background they stand on (legs the same value as the floor disappear).

## Director pass (contact sheet at 2 fps)

- [ ] Pace fits the form (pace table in `storyboard.md`): quick for comedy, slow and held for ambient or lullaby. The failure is a hold with nothing happening, not a long shot.
- [ ] Framing varies (wide / medium / close / extreme close); at least one push-in or pull-out.
- [ ] No dead frames: every shot has something alive (a camera drift, a breathing motion, light changing), even when it's slow.
- [ ] Every visible action has its sound in `EVENTS`.
- [ ] The look fits the audience and matches the look brief (style, palette, line, ground, type). For an adult audience, no accidental defaults: everything rounded, outlines on every shape, many equal saturated colours, flat front-on staging, always-centred subjects.
- [ ] It doesn't look or sound like your previous piece.

## Motion

- [ ] A hand-drawn line boils at ~7.5 changes/s (every 4 frames), not every frame.
- [ ] Endings hold: the last line appears after motion has settled.
- [ ] Loops: frame 0 and the last frame match.

## Facts and assets

- [ ] Every fact on screen has a source you can name.
- [ ] `node scripts/asset-audit.mjs page.html` prints CLEAN.
- [ ] If there's a soundtrack: `node ../soundtrack/scripts/sync-check.mjs out.mp4` passes (on the beat, no startle).
- [ ] Private material (family photos, names) stays local and out of anything published.
```

## File: skills/javascript-animation/references/storyboard.md
size: 4666
sha: 60b93afe3f695217afd332aa949e0e2d83abe512
upstream: https://github.com/iart-ai/javascript-animation-skills/blob/main/skills/javascript-animation/references/storyboard.md

```text
# Storyboard, blocking and the beat grid

Write these before any drawing code. They are data in the page (`BPM`, `SECTIONS`, `SHOTS`, `EVENTS`, blocking constants), not notes: the scenes, the camera and the soundtrack all read them, so picture and sound land together by construction.

The starter already has the skeleton. This is a self-check step: don't stop to ask the user to approve the storyboard. Deliver it with the film (e.g. as `storyboard.md`) so they can point at a shot to change.

## 1. Beat grid

- Pick a tempo from the mood of this film. `b(n)` is the n-th beat in seconds.
- Pick a shape for the sections that fits the piece, for example:
  - **escalation**: intro, build, peak, break, payoff (comedy, reveals)
  - **steady**: one texture that breathes and evolves, no drop (ambient, lullaby, poem)
  - **steps**: a short motif per step, a pause between steps, a resolve at the end (explainers)
  - **verse/return**: a theme, a contrast, the theme again (stories)
  A short silence before a payoff is a strong beat when the piece has one; a lullaby may never need it.
- Every cut and every visible action sits on a beat or a half beat.

## 2. Shot list

One row per shot. Pick the pace from the form:

| Form | Typical shot length |
|---|---|
| Comedy, hype | 1-3 s |
| Story | 2-5 s |
| Explainer | 3-6 s (one idea per shot) |
| Lullaby, ambient, poem | 5-10 s, long dissolves |

A long shot is fine; a long shot where nothing is alive is not.

| # | from–to (beats) | framing | camera move | what happens (the action) | blocking | action lands on | sound | transition |
|---|---|---|---|---|---|---|---|---|
| 4 | 12–16 | close-up | slow push | the kettle starts to whistle and the lid rattles | kettle centre-left; steam rises out of frame top right | beats 13, 14 (rattles), 15 (whistle) | tick, tick, whistle | match cut on the steam |

- **Vary framing**: wide, medium, close, extreme close. Scale changes are what makes a short feel cinematic.
- **Keep every shot alive**: a slow push or drift on the camera, or at least one secondary motion (smoke, breathing, light changing), at whatever pace the form wants.
- **Vary transitions**: hard cut, match cut, push into / pull out of an object (a screen, a window, an eye). Save the dip-to-paper for chapter breaks.

## 3. Blocking: one world, many cameras

This is how a story or an explainer holds together. A film that is neither (a title sequence, a film of type, a showreel) holds together by rhythm and one visual idea, and may cut between worlds; its blocking is per world.

- Put every character and prop in **one continuous world** with a track over global time (where it is, its pose, its expression). Shots are only cameras looking at that world (`withCamera`). A cut then can't break continuity: the end of one shot is literally the start of the next.
- Continuity rules the world model doesn't give you for free:
  - **Carry something over every cut**: the same object crosses the cut, or the camera pushes into a detail that becomes the next scene.
  - **Screen direction**: something moving right keeps moving right across a cut.
  - **Props, light and time of day persist**: what's in a hand stays in the hand; night doesn't become day without a transition. Share the sky between a window in the room and the world outside.
- **Staging that reads as real**: things rest on surfaces (a monitor on a desk, with a stand), people have feet on the floor, objects don't hover unless that's the joke. Someone at a computer reads best over the shoulder, with the screen facing the camera.

## 4. Story logic

- **Every beat is caused by the previous one.** "Does A, then notices B" is flat; "doing A causes B" is a chain the audience feels. Escalation should be causal.
- **Show the metaphor in the picture.** If an object stands for an idea, draw the idea onto it, visibly. A label next to an unexplained picture doesn't land.
- **Punchlines get their own shot**: a reveal (what happened), then a reverse shot of the reaction (the face). Cut between them on a beat.

## 5. Events

`EVENTS` lists every visible action with a sound: `[[seconds, 'soundName', arg], ...]`. The scenes trigger the action at the same time; the score (soundtrack skill) plays its sound. One list, two readers.

## 6. Check the picture against the storyboard

After the first render, take a still at the action beat of every shot (`render.mjs page.html shot --stills ...`) and read it against its row: is the actor where the blocking says, doing what the row says, and can you tell what just happened? Most "the video doesn't match the script" problems are blocking that was never written into the tracks.
```

## File: skills/javascript-animation/references/techniques.md
size: 10243
sha: a39422b5f0eaac0d2fba7e6adb994e8539c36926
upstream: https://github.com/iart-ai/javascript-animation-skills/blob/main/skills/javascript-animation/references/techniques.md

````text
# Drawing techniques

Techniques, not presets. Each one is a way of making marks; the palette, scale and combination come from the subject (see "Derive the look" below). All snippets assume the helpers in `templates/starter.html` (`ctx`, `W`, `H`, `rng`, `hash2`, `clamp`, `lerp`, `ink`, `fill`, `tracePath`, `J`, `circle`, `rect`, `arc`, `resample`).

**How tested each one is** (be honest with the user about this):

| Technique | Status |
|---|---|
| 1. Ink line (hand-drawn) | Used across two full films |
| 2. Illustration shapes (picture-book) | Used across a full film |
| 3. Spot-color print (riso) | Renders correctly as a still; not yet used in a full film |
| 4. Single-line engraving | Renders correctly as a still; not yet used in a full film |
| 5. Words as the shape | Renders correctly as a still; not yet used in a full film |
| 6. Marker / gouache fill | Renders correctly as a still; not yet used in a full film |
| 7. Cinematic flat + blueprint | Used across a full film (the "fix one line" example) |

## Derive the look

Before drawing, write down what the subject is made of and let that pick the marks:
- a newborn's-vision explainer: black-and-white cards, so ink on paper, one warm accent;
- a baby's day for the family: soft, picture-book shapes, the actual colors of the nursery;
- a typhoon explainer: wind and water, so words-as-shape spirals, blues;
- a print-shop or zine topic: spot-color layers.

Two different subjects should not come out looking alike. Don't carry a palette over from the example or an earlier piece.

## 1. Ink line (in the starter)

`ink(pts, { w, col, seed, amp, passes })` strokes a path through two-frequency noise; with `LOOK.wobble` set, edges wobble like a pen and the path is stroked twice (a full line and a thinner, fainter second pass). With `wobble: 0` it is one steady line. `fill`, `hatch` (parallel strokes clipped to a shape), `withShadow` (the same shape offset a few px in a translucent ink) and the paper texture complete the look. Set `LOOK.boil: 4` so the wobble changes ~7.5x per second.

Tuning: `amp` 1-2.5 px (higher is sketchier); two passes for pen, one for marker; hatch `gap` 6-12 px, alpha 0.2-0.4.

## 2. Illustration shapes (in the starter)

`shape(pts, col, { shadow, shade, tex, lw, line })`: base fill, a darker rim toward the bottom-right (fill dark, then the shape again nudged up-left), a few translucent lighter brush strokes, and an outline in a darker tint of the fill (`tint(col, .6)`), never flat black. Add `blush(x, y, rx, ry)` for soft radial cheeks or glows. Keep the ink wobble low (`amp` ~1) so it reads as illustration, not sketch.

## 3. Spot-color print (risograph)

Draw each ink color on its own layer, knock it slightly out of register, grain it, then multiply. Overlaps produce new colors for free.

```js
function spotLayers(layers, { offset = 4, grain = .18, seed = 1 } = {}) {
  // layers: [{ color, draw: () => { /* fill shapes with any color; only the alpha is used */ } }, ...]
  const r = rng(seed);
  for (const L of layers) {
    const c = document.createElement('canvas'); c.width = W; c.height = H;
    const main = ctx; ctx = c.getContext('2d'); L.draw(); ctx = main;          // shape mask
    const x = c.getContext('2d');
    x.globalCompositeOperation = 'source-in'; x.fillStyle = L.color; x.fillRect(0, 0, W, H); // tint
    x.globalCompositeOperation = 'destination-out';                               // ink grain
    for (let i = 0; i < W * H / 60; i++) { x.globalAlpha = r() * grain; x.fillRect(r() * W, r() * H, 2, 2); }
    ctx.save(); ctx.globalCompositeOperation = 'multiply';
    ctx.drawImage(c, (r() - .5) * offset * 2, (r() - .5) * offset * 2);           // misregistration
    ctx.restore();
  }
}
```

Usage: `spotLayers([{ color: '#ff4f8b', draw: () => fill(circle(200, 230, 140), '#000') }, { color: '#1f9e9a', draw: () => ... }], { seed: 4 })`. Two or three inks; any fill color inside `draw` works (only its alpha is used). It allocates a full-size canvas per layer per frame: fine for rendering, heavy for live preview at 60 fps.

## 4. Single-line engraving

One continuous spiral whose thickness follows a brightness field you write in code (0 = dark, 1 = light). The line width is capped by the gap between turns, or everything fills in solid.

```js
function spiralShade(cx, cy, R, brightness, { turns = 40, col = INK } = {}) {
  const maxW = R / turns * .95; // never thicker than the gap between turns, or it all fills in
  ctx.save(); ctx.strokeStyle = col; ctx.lineCap = 'round';
  let prev = null;
  for (let a = 0; a < turns * Math.PI * 2; a += .04) {
    const r = R * a / (turns * Math.PI * 2), x = cx + Math.cos(a) * r, y = cy + Math.sin(a) * r;
    if (prev) { ctx.lineWidth = .3 + maxW * (1 - clamp(brightness(x, y))); ctx.beginPath(); ctx.moveTo(...prev); ctx.lineTo(x, y); ctx.stroke(); }
    prev = [x, y];
  }
  ctx.restore();
}
```

Example field, a sphere lit from the upper left:
`(x, y) => { const dx = (x - cx) / R, dy = (y - cy) / R, r2 = dx * dx + dy * dy; if (r2 > 1) return .96; return clamp(.1 + .9 * Math.max(0, -.45 * dx - .55 * dy + .7 * Math.sqrt(1 - r2))); }`

## 5. Words as the shape

Fill a region with a repeated phrase so the words are the picture, or set a phrase along a path.

```js
function textFill(pts, phrase, { size = 18, col = INK, lead = 1.25, drift = 0 } = {}) {
  const xs = pts.map(p => p[0]), ys = pts.map(p => p[1]);
  ctx.save(); tracePath(pts, true); ctx.clip();
  ctx.font = `700 ${size}px ui-monospace, monospace`; ctx.fillStyle = col; ctx.textBaseline = 'top';
  const unit = phrase + '  ', uw = ctx.measureText(unit).width;
  for (let y = Math.min(...ys), row = 0; y < Math.max(...ys); y += size * lead, row++) {
    const x0 = Math.min(...xs) - uw + ((row * uw * .37 + drift * (row % 2 ? 1 : -1)) % uw + uw) % uw;
    for (let x = x0; x < Math.max(...xs); x += uw) ctx.fillText(unit, x, y);
  }
  ctx.restore();
}
// Or set a phrase along any path (a spiral, a wave, an orbit).
function textOnPath(pts, text, { size = 22, col = INK, start = 0 } = {}) {
  ctx.save(); ctx.font = `700 ${size}px ui-monospace, monospace`; ctx.fillStyle = col; ctx.textBaseline = 'middle';
  let d = start, i = 0, acc = 0;
  for (const ch of text) {
    const w = ctx.measureText(ch).width;
    while (i < pts.length - 1 && acc + Math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]) < d) { acc += Math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]); i++; }
    if (i >= pts.length - 1) break;
    const [x0, y0] = pts[i], [x1, y1] = pts[i + 1], seg = Math.hypot(x1 - x0, y1 - y0), k = (d - acc) / seg;
    ctx.save(); ctx.translate(lerp(x0, x1, k), lerp(y0, y1, k)); ctx.rotate(Math.atan2(y1 - y0, x1 - x0)); ctx.fillText(ch, 0, 0); ctx.restore();
    d += w;
  }
  ctx.restore();
}
```

Good for explainers: the label and the thing become one ("warm water" rows make the sea; "air spins inward" makes the spiral).

## 6. Marker / gouache fill

Overlapping broad strokes in one direction, each a slightly different tint, semi-opaque, rounded ends.

```js
function markerFill(pts, color, { angle = -.5, width = 26, seed = 3, alpha = .82, vary = 14 } = {}) {
  const r = rng(seed), xs = pts.map(p => p[0]), ys = pts.map(p => p[1]);
  const cx = (Math.min(...xs) + Math.max(...xs)) / 2, cy = (Math.min(...ys) + Math.max(...ys)) / 2;
  const R = Math.hypot(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys)) / 2;
  const base = [1, 3, 5].map(i => parseInt(color.substr(i, 2), 16));
  ctx.save(); tracePath(J(pts, seed, 2), true); ctx.clip();
  ctx.translate(cx, cy); ctx.rotate(angle); ctx.lineCap = 'round';
  for (let y = -R; y < R; y += width * .62) {
    const v = (r() - .5) * vary;
    ctx.strokeStyle = `rgb(${base.map(c => clamp(c + v, 0, 255) | 0).join(',')})`;
    ctx.globalAlpha = alpha; ctx.lineWidth = width * (.85 + r() * .3);
    ctx.beginPath(); ctx.moveTo(-R - 10, y + (r() - .5) * 6); ctx.lineTo(R + 10, y + (r() - .5) * 6); ctx.stroke();
  }
  ctx.restore();
}
```

## No house style

Pick the look from the subject and the audience; the techniques below are ingredients, not presets.

## 7. Cinematic flat + blueprint (in the starter)

`flatMass(pts, col)` fills a shape with a shadow side and no outline. `guide(pts, t0, t)` draws a dashed construction outline that fades as the real thing appears at `t0` (show structures being "drawn up" before they fill in). `glow(x, y, r, [r,g,b], a)` is a soft radial light. Keep line widths constant on screen under zoom by multiplying by `PX`. Grain comes from the paper texture multiplied over the frame.

## Depth without 3D (a road, a river, a corridor)

Put a horizon at `HZ` and a vanishing x. Give each moving thing a depth `d` in 0..1 that loops with time (`d = (k / N + t * speed) % 1`); its screen row is `y = HZ + (H - HZ) * d * d` and its scale `lerp(.08, 1.6, d * d)`. Stripes across the path at those rows rush toward the viewer; objects placed at the path edge (± half-width at that row) grow as they pass. The squared depth is what makes it read as perspective. Used for a stroller-eye view down a park path.

## Canvas gotchas

- **Build gradients after the transform they live in.** `createRadialGradient(x, y, …)` then `translate(x, y)` moves the gradient off by (x, y) again, and the fill silently shows nothing. Translate/scale first, then create the gradient at (0, 0).
- **`ctx.filter` blur and saturate** work in headless Chrome and in the render; they are the cheapest way to show "how someone else sees it" (see `drawLayer`).
- **Monospace fonts lack many glyphs** (`≈`, arrows, CJK) and swap them silently. Check the stills; use a font stack that has the characters.
- **`-x ** y` is a syntax error** in JS; write `-(x ** y)`.

## Motion building blocks (in the starter)

- `drawOn(pts, p)`: reveal a stroke from 0 to 1 (a line being drawn).
- `label(text, x, y, { p })`: a paper-tape tag that types on; its box grows with the typed text.
- `drawLayer(fn, filter, clip)`: draw into an offscreen layer and composite with a CSS filter (`blur()`, `saturate()`, `contrast()`) and optional clip, e.g. a before/after slider.
- Easing: `ease`, `easeOut`, `back` (overshoot pop), `prog(t, a, b)` for a 0-1 ramp between two times.
````

## File: skills/javascript-animation/templates/starter.html
size: 19510
sha: 8703adfc360e293581b2abba9c0a5921a581f142
upstream: https://github.com/iart-ai/javascript-animation-skills/blob/main/skills/javascript-animation/templates/starter.html

```text
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled animation</title>
<style>
  html,body{margin:0;background:#1b1917;display:grid;place-items:center;height:100vh}
  canvas{width:min(100vw,100vh);height:auto;max-height:100vh}
</style>
</head>
<body>
<canvas id="c" width="1920" height="1080"></canvas>
<script>
// Starter for a zero-asset, code-drawn animation. Every pixel is computed; nothing is loaded.
// Contract (render.mjs relies on it): draw(frame) is a pure function of the frame number,
// so any frame can be rendered alone, in any order. Never use Math.random or Date here:
// use rng(seed) / hash2() so the same frame always looks the same.
const W = 1920, H = 1080, FPS = 30, DUR = 6, FRAMES = FPS * DUR;
const cv = document.getElementById('c');
cv.width = W; cv.height = H;
let ctx = cv.getContext('2d');

// LOOK: every value here is a choice for THIS piece, not a default to keep. Decide each one from the
// subject and the audience (references/techniques.md); don't carry choices over from
// a previous piece. The palette below is deliberately grey: it is not a palette, only names to replace.
// Choose real colours for this piece (3-5, one lead) and rename them.
const PAPER = '#f2f2f2', INK = '#1a1a1a', RED = '#8c8c8c', BLUE = '#5c5c5c',
      YELLOW = '#b8b8b8', SHADOW = 'rgba(0,0,0,0.16)';
const LOOK = {
  ground: 'flat',      // background: 'flat' (clean colour) | 'grain' (colour + fine noise) | 'paper' (grain, fibres, vignette)
  wobble: 0,           // edge wobble: 0 = steady lines; a hand-drawn film sets 1 = pen, 2+ = loose sketch
  boil: 0,             // redraw the wobble every N frames (line boil); 0 = steady, 4 = ~7.5x/sec like hand animation
  font: '600 {s}px -apple-system, "Helvetica Neue", Arial, sans-serif',   // choose a family that fits: serif, rounded, mono, condensed, script...
  labelStyle: 'plain', // 'plain' (text) | 'pill' (rounded box) | 'tag' (paper tape) | 'underline'
  guideColor: INK,     // construction-line colour (blue only if the piece is a blueprint)
};

// ---------- math ----------
const clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));
const lerp = (a, b, t) => a + (b - a) * t;
const ease = t => { t = clamp(t); return t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; };
const easeOut = t => 1 - Math.pow(1 - clamp(t), 3);
const back = t => { t = clamp(t); const c = 1.7; return 1 + (c + 1) * Math.pow(t - 1, 3) + c * Math.pow(t - 1, 2); };
const prog = (t, a, b) => clamp((t - a) / (b - a));

function hash2(a, b) {
  let n = Math.imul(a | 0, 374761393) + Math.imul(b | 0, 668265263);
  n = Math.imul(n ^ (n >>> 13), 1274126177);
  return ((n ^ (n >>> 16)) >>> 0) / 4294967295;
}
function vnoise(x, y) {
  const xi = Math.floor(x), yi = Math.floor(y), xf = x - xi, yf = y - yi;
  const u = xf * xf * (3 - 2 * xf), v = yf * yf * (3 - 2 * yf);
  return lerp(lerp(hash2(xi, yi), hash2(xi + 1, yi), u), lerp(hash2(xi, yi + 1), hash2(xi + 1, yi + 1), u), v);
}
function rng(seed) { let a = seed | 0; return () => { a = a + 0x6D2B79F5 | 0; let t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; }; }

// ---------- hand-drawn primitives ----------
let BOIL = 0;          // changes every LOOK.boil frames -> "line boil" (0 = steady)
let SHADOWING = false; // when true, primitives paint the drop shadow color

function jit(x, y, seed, amp) {
  const s = seed * 13.37;
  return [
    x + (vnoise(x * .012 + s, y * .012) - .5) * 2 * amp + (vnoise(x * .09 + s, y * .09 + 7) - .5) * amp * .6,
    y + (vnoise(x * .012, y * .012 + s + 50) - .5) * 2 * amp + (vnoise(x * .09 + 3, y * .09 + s) - .5) * amp * .6,
  ];
}
function resample(pts, step = 9, closed = false) {
  const out = [], P = closed ? [...pts, pts[0]] : pts;
  for (let i = 0; i < P.length - 1; i++) {
    const [x0, y0] = P[i], [x1, y1] = P[i + 1], n = Math.max(1, Math.ceil(Math.hypot(x1 - x0, y1 - y0) / step));
    for (let k = 0; k < n; k++) out.push([lerp(x0, x1, k / n), lerp(y0, y1, k / n)]);
  }
  if (!closed) out.push(P[P.length - 1]);
  return out;
}
function tracePath(pts, closed) {
  ctx.beginPath();
  if (pts.length < 3) { ctx.moveTo(...pts[0]); pts.slice(1).forEach(p => ctx.lineTo(...p)); if (closed) ctx.closePath(); return; }
  const P = closed ? [...pts, pts[0], pts[1]] : pts;
  ctx.moveTo(...(closed ? [(P[0][0] + P[1][0]) / 2, (P[0][1] + P[1][1]) / 2] : P[0]));
  for (let i = 1; i < P.length - 1; i++) ctx.quadraticCurveTo(P[i][0], P[i][1], (P[i][0] + P[i + 1][0]) / 2, (P[i][1] + P[i + 1][1]) / 2);
  if (!closed) ctx.lineTo(...P[P.length - 1]); else ctx.closePath();
}
const J = (pts, seed, amp) => pts.map(([x, y]) => jit(x, y, BOIL + seed, amp * LOOK.wobble));

function ink(pts, o = {}) {
  const { w = 4, col = INK, closed = false, amp = 2, seed = 0, passes = LOOK.wobble ? 2 : 1, alpha = 1 } = o;   // 2 = pen, 1 = a steady line
  ctx.save(); ctx.lineCap = ctx.lineJoin = 'round';
  for (let p = 0; p < passes; p++) {
    ctx.globalAlpha = alpha * (p ? .45 : 1);
    ctx.strokeStyle = SHADOWING ? SHADOW : col;
    ctx.lineWidth = w * (p ? .55 : 1);
    tracePath(J(pts, seed + p * .41, amp * (p ? 1.4 : 1)), closed);
    ctx.stroke();
  }
  ctx.restore();
}
function fill(pts, col, o = {}) {
  const { amp = 1.6, seed = 0, alpha = 1 } = o;
  ctx.save(); ctx.globalAlpha = alpha; ctx.fillStyle = SHADOWING ? SHADOW : col;
  tracePath(J(pts, seed + .2, amp), true); ctx.fill(); ctx.restore();
}
function hatch(pts, o = {}) {
  if (SHADOWING) return;
  const { angle = -0.9, gap = 11, col = INK, w = 1.6, alpha = .35, seed = 0 } = o;
  const xs = pts.map(p => p[0]), ys = pts.map(p => p[1]);
  const cx = (Math.min(...xs) + Math.max(...xs)) / 2, cy = (Math.min(...ys) + Math.max(...ys)) / 2;
  const R = Math.hypot(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys)) / 2 + 10;
  ctx.save(); tracePath(J(pts, seed, 1.5), true); ctx.clip();
  ctx.translate(cx, cy); ctx.rotate(angle);
  ctx.strokeStyle = col; ctx.lineWidth = w; ctx.globalAlpha = alpha; ctx.lineCap = 'round';
  for (let y = -R, i = 0; y < R; y += gap, i++) {
    const a = hash2(i, BOIL + seed * 7) * 4 - 2, b = hash2(i + 99, BOIL + seed * 7) * 4 - 2;
    ctx.beginPath(); ctx.moveTo(-R, y + a); ctx.quadraticCurveTo(0, y + (a + b), R, y + b); ctx.stroke();
  }
  ctx.restore();
}
function withShadow(fn, dx = 9, dy = 9) {
  ctx.save(); ctx.translate(dx, dy); SHADOWING = true; fn(); SHADOWING = false; ctx.restore(); fn();
}

// shapes
const circle = (cx, cy, r, ry = r, rot = 0) => {
  const n = Math.max(20, Math.round(Math.max(r, ry) * .45)), out = [];
  for (let i = 0; i < n; i++) { const a = i / n * Math.PI * 2, x = Math.cos(a) * r, y = Math.sin(a) * ry;
    out.push([cx + x * Math.cos(rot) - y * Math.sin(rot), cy + x * Math.sin(rot) + y * Math.cos(rot)]); }
  return out;
};
const rect = (x, y, w, h) => resample([[x, y], [x + w, y], [x + w, y + h], [x, y + h]], 12, true);
const line = (x0, y0, x1, y1) => resample([[x0, y0], [x1, y1]], 10);
const arc = (cx, cy, r, a0, a1, ry = r) => { const n = Math.max(8, Math.round(Math.abs(a1 - a0) * r / 9)), o = [];
  for (let i = 0; i <= n; i++) { const a = lerp(a0, a1, i / n); o.push([cx + Math.cos(a) * r, cy + Math.sin(a) * ry]); } return o; };
const roundRect = (x, y, w, h, r) => resample([
  ...arc(x + w - r, y + r, r, -Math.PI / 2, 0), ...arc(x + w - r, y + h - r, r, 0, Math.PI / 2),
  ...arc(x + r, y + h - r, r, Math.PI / 2, Math.PI), ...arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)], 10, true);

// labels, typed on; their look comes from LOOK.labelStyle and LOOK.font
const FONT = LOOK.font;
function label(text, x, y, o = {}) {
  const { size = 40, bg = BLUE, fg = PAPER, p = 1, align = 'left', rot = LOOK.labelStyle === 'tag' ? -0.015 : 0, seed = 3, style = LOOK.labelStyle } = o;
  if (p <= 0) return;
  ctx.save(); ctx.font = FONT.replace('{s}', size);
  const n = Math.round(text.length * clamp((p - .1) / .9)), shown = text.slice(0, n);
  const full = ctx.measureText(text).width, padX = size * .45, h = size * 1.45;
  const w = Math.max(size, ctx.measureText(shown).width) + padX * 2;
  const x0 = align === 'center' ? x - (full + padX * 2) / 2 : align === 'right' ? x - w : x;
  ctx.translate(x0 + w / 2, y); ctx.rotate(rot); ctx.translate(-(x0 + w / 2), -y);
  const sc = easeOut(p * 3);
  ctx.translate(x0, y); ctx.scale(1, sc); ctx.translate(-x0, -y);
  if (style === 'tag') { const box = rect(x0, y - h / 2, w, h); withShadow(() => fill(box, bg, { seed }), 6, 6); }
  else if (style === 'pill') { ctx.fillStyle = bg; ctx.beginPath(); ctx.roundRect(x0, y - h / 2, w, h, h / 2); ctx.fill(); }
  else if (style === 'underline') { ctx.fillStyle = bg; ctx.fillRect(x0 + padX, y + size * .55, w - padX * 2, Math.max(2, size * .08)); }
  ctx.fillStyle = style === 'plain' || style === 'underline' ? (o.fg || INK) : fg; ctx.textBaseline = 'middle';
  ctx.fillText(shown, x0 + padX, y + 1);
  ctx.restore();
}
function note(text, x, y, o = {}) { // plain handwritten-ish ink text
  const { size = 26, col = INK, align = 'center', alpha = 1 } = o;
  ctx.save(); ctx.globalAlpha = alpha; ctx.font = FONT.replace('{s}', size); ctx.fillStyle = col;
  ctx.textAlign = align; ctx.textBaseline = 'middle'; ctx.fillText(text, x, y); ctx.restore();
}

// reveal a stroke progressively (0..1): hand-drawing a line onto the page
function drawOn(pts, p, o = {}) {
  const n = Math.max(2, Math.round(pts.length * clamp(p)));
  if (p > 0) ink(pts.slice(0, n), o);
}

// ---------- illustration primitives (a second look; use these OR the ink ones, per concept) ----------
// Picture-book shapes: outline in a darker tint of the fill (not black), inner shade, brush texture.
const rgbOf = h => [1, 3, 5].map(i => parseInt(h.substr(i, 2), 16));
const tint = (h, k) => `rgb(${rgbOf(h).map(v => Math.round(k < 1 ? v * k : v + (255 - v) * (k - 1))).join(',')})`; // k<1 darker, k>1 toward white
const bbox = pts => { const xs = pts.map(p => p[0]), ys = pts.map(p => p[1]); return [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)]; };
function shape(pts, col, o = {}) {
  const { line = tint(col, .6), lw = 3.5, seed = 0, tex = true, shade = true, shadow = false, alpha = 1 } = o;
  if (shadow) { ctx.save(); ctx.translate(8, 10); fill(pts, 'rgba(90,60,40,.12)', { seed, amp: 1 }); ctx.restore(); }
  fill(pts, col, { seed, amp: 1, alpha });
  if (tex || shade) {
    const [x0, y0, x1, y1] = bbox(pts), bw = x1 - x0, bh = y1 - y0;
    ctx.save(); tracePath(J(pts, seed + .2, 1), true); ctx.clip(); ctx.globalAlpha = alpha;
    if (shade) { // darker rim toward bottom-right: fill dark, then the shape again nudged up-left
      ctx.fillStyle = tint(col, .8); ctx.fillRect(x0 - 5, y0 - 5, bw + 10, bh + 10);
      ctx.translate(-bw * .07, -bh * .09); fill(pts, col, { seed, amp: 1 }); ctx.translate(bw * .07, bh * .09);
    }
    if (tex) { // a few translucent lighter brush strokes
      const r = rng((Math.abs(seed * 97) | 0) + 1); ctx.lineCap = 'round'; ctx.strokeStyle = tint(col, 1.35);
      for (let i = 0; i < 10; i++) { ctx.globalAlpha = .1 + r() * .1; ctx.lineWidth = 6 + r() * 10; const y = y0 + r() * bh, x = x0 + r() * bw * .5;
        ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + bw * (.2 + r() * .4), y - bh * .1 * r()); ctx.stroke(); }
    }
    ctx.restore();
  }
  if (lw) ink(pts, { closed: true, w: lw, col: line, seed, amp: 1, passes: 1, alpha });
}
function blush(x, y, rx, ry, a = .5) { // soft radial cheek / glow
  ctx.save(); ctx.translate(x, y); ctx.scale(1, ry / rx); // gradient is built in the transformed space
  const g = ctx.createRadialGradient(0, 0, 0, 0, 0, rx);
  g.addColorStop(0, `rgba(236,130,115,${a})`); g.addColorStop(1, 'rgba(236,130,115,0)');
  ctx.fillStyle = g; ctx.beginPath(); ctx.arc(0, 0, rx, 0, 7); ctx.fill(); ctx.restore();
}

// ---------- flat / blueprint primitives (the "cinematic flat" look; no outlines, value does the work) ----------
function flatMass(pts, col, o = {}) {           // a flat shape with a shadow side, no outline
  const { alpha = 1, shade = .18 } = o;
  ctx.save(); ctx.globalAlpha = alpha; ctx.fillStyle = col; ctx.beginPath(); ctx.moveTo(...pts[0]); for (const p of pts.slice(1)) ctx.lineTo(...p); ctx.closePath(); ctx.fill();
  if (shade) { const [x0, y0, x1, y1] = bbox(pts); ctx.clip(); ctx.fillStyle = `rgba(10,12,30,${shade})`; ctx.fillRect(x0 + (x1 - x0) * .7, y0, (x1 - x0) * .32, y1 - y0); }
  ctx.restore();
}
function guide(pts, t0, t, o = {}) {            // dashed construction line that fades as the real thing fills in
  const a = (o.alpha ?? .7) * (1 - prog(t, t0 + .25, t0 + .6)); if (a <= 0) return;
  ctx.save(); ctx.globalAlpha = a; ctx.strokeStyle = o.col || LOOK.guideColor; ctx.lineWidth = 1.4 * PX; ctx.setLineDash([6 * PX, 5 * PX]);
  ctx.beginPath(); ctx.moveTo(...pts[0]); for (const p of pts.slice(1)) ctx.lineTo(...p); if (o.closed !== false) ctx.closePath(); ctx.stroke(); ctx.restore();
}
function glow(x, y, r, rgb, a) {                 // soft light: rgb as [r, g, b]
  ctx.save(); const g = ctx.createRadialGradient(x, y, 0, x, y, r); g.addColorStop(0, `rgba(${rgb},${a})`); g.addColorStop(1, `rgba(${rgb},0)`); ctx.fillStyle = g; ctx.fillRect(x - r, y - r, 2 * r, 2 * r); ctx.restore();
}

// ---------- one world, many cameras ----------
let PX = 1;                                      // world units per screen pixel under the current camera: multiply line widths by it
function withCamera(cam, fn) {                   // cam = { cx, cy, k }: world point at the screen centre, and zoom
  ctx.save(); ctx.translate(W / 2, H / 2); ctx.scale(cam.k, cam.k); ctx.translate(-cam.cx, -cam.cy); const px = PX; PX = 1 / cam.k;
  fn(); PX = px; ctx.restore();
}

// ---------- layout registry: claim what must not collide (read by scripts/layout-check.mjs) ----------
let LAYOUT = [];
function claim(id, kind, x, y, w, h) {           // kind: 'text' | 'keep'; box in the current transform
  const m = ctx.getTransform(), P = [[x, y], [x + w, y], [x, y + h], [x + w, y + h]].map(([a, c]) => [m.a * a + m.c * c + m.e, m.b * a + m.d * c + m.f]);
  const xs = P.map(p => p[0]), ys = P.map(p => p[1]); LAYOUT.push({ id, kind, x: Math.min(...xs), y: Math.min(...ys), w: Math.max(...xs) - Math.min(...xs), h: Math.max(...ys) - Math.min(...ys) });
}
function placeFree(w, h, candidates) {           // first candidate box [x, y] that overlaps nothing claimed so far this frame
  const free = ([x, y]) => LAYOUT.every(o => x + w <= o.x || o.x + o.w <= x || y + h <= o.y || o.y + o.h <= y);
  return candidates.find(free) || candidates[0];
}

// ---------- paper ----------
const paper = document.createElement('canvas'); paper.width = W; paper.height = H;
(() => {
  const p = paper.getContext('2d'), r = rng(7);
  p.fillStyle = PAPER; p.fillRect(0, 0, W, H);
  if (LOOK.ground === 'flat') return;
  for (let i = 0; i < 90000; i++) { p.fillStyle = r() < .5 ? 'rgba(90,70,50,0.05)' : 'rgba(255,255,255,0.08)';
    p.fillRect(r() * W, r() * H, 1 + r() * 1.5, 1 + r() * 1.5); }
  if (LOOK.ground === 'grain') return;
  p.strokeStyle = 'rgba(120,95,70,0.06)'; p.lineWidth = 1;
  for (let i = 0; i < 260; i++) { const x = r() * W, y = r() * H, a = r() * 6.28, l = 6 + r() * 22;
    p.beginPath(); p.moveTo(x, y); p.quadraticCurveTo(x + Math.cos(a) * l / 2 + 3, y + Math.sin(a) * l / 2, x + Math.cos(a) * l, y + Math.sin(a) * l); p.stroke(); }
  const g = p.createRadialGradient(W / 2, H / 2, W * .35, W / 2, H / 2, W * .75);
  g.addColorStop(0, 'rgba(0,0,0,0)'); g.addColorStop(1, 'rgba(60,40,20,0.13)'); p.fillStyle = g; p.fillRect(0, 0, W, H);
})();

// offscreen layer for filtered (blurred / desaturated) drawing
const layer = document.createElement('canvas'); layer.width = W; layer.height = H;
function drawLayer(fn, filter, clip) {
  const main = ctx, l = layer.getContext('2d');
  l.clearRect(0, 0, W, H); ctx = l; fn(); ctx = main;
  ctx.save(); if (clip) { ctx.beginPath(); ctx.rect(...clip); ctx.clip(); }
  ctx.filter = filter || 'none'; ctx.drawImage(layer, 0, 0); ctx.restore();
}

// ---------- storyboard: the single source of truth ----------
// Beat grid first, then shots and blocking, then code. Scenes, camera and soundtrack all read these.
const BPM = 120, BEAT = 60 / BPM, b = n => n * BEAT;            // b(8) = the 8th beat, in seconds
const SECTIONS = [[0, 1, ['pad']], [1, 2, ['pad', 'hat8']], [2, 3, ['pad', 'hat8', 'kick2']], [3, 4, ['pad', 'kick4', 'hat8', 'clap']]];   // bars -> music layers; add one or two layers per bar
const SHOTS = [                                                  // one world, many cameras; every cut on a beat
  { from: 0, to: b(8), cam: t => ({ cx: 0, cy: -120, k: 1 + .06 * prog(t, 0, b(8)) }) },          // wide, slow push
  { from: b(8), to: DUR, cam: t => ({ cx: 0, cy: -60, k: 2.4 }) },                                 // close-up
];
const BOX = { x: -40, drop: b(4), bounce: b(9) };                 // blocking: where the actor is, and when
const EVENTS = [[b(4) + .3, 'thud'], [b(9), 'boing'], [b(10), 'ding']];   // [seconds, sfx]: one sound per visible action

// ---------- the world, drawn in world coordinates ----------
function world(t) {
  ctx.fillStyle = '#d9d2c3'; ctx.fillRect(-2000, 0, 4000, 2000);                                   // floor
  guide(boxR(BOX.x, -80, 80, 80), BOX.drop - .4, t);                                                // where it will land
  const land = back(prog(t, BOX.drop, BOX.drop + .3)), hop = t > BOX.bounce ? Math.sin(prog(t, BOX.bounce, BOX.bounce + .5) * Math.PI) * 40 : 0;
  if (t > BOX.drop) { const y = lerp(-900, -80, land) - hop; flatMass(box(BOX.x, y, 80, 80), RED); claim('box', 'keep', BOX.x, y, 80, 80); }
}
const box = (x, y, w, h) => [[x, y], [x + w, y], [x + w, y + h], [x, y + h]];
const boxR = (x, y, w, h) => resample(box(x, y, w, h), 10, true);

function draw(frame) {
  const t = frame / FPS;
  BOIL = LOOK.boil ? Math.floor(frame / LOOK.boil) : 0; LAYOUT = [];   // LOOK.boil 4 = wobble redrawn ~7.5x/sec, like hand animation
  ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.filter = 'none'; ctx.globalAlpha = 1;
  ctx.drawImage(paper, 0, 0);
  const shot = SHOTS.find(s => t >= s.from && t < s.to) || SHOTS[SHOTS.length - 1];
  withCamera(shot.cam(t), () => world(t));
  if (t > b(10)) { const w = 360, h = 64, [x, y] = placeFree(w, h, [[W / 2 - w / 2, 160], [W / 2 - w / 2, 820]]);   // text steps aside from claimed things
    label('landed.', x + 20, y + h / 2, { size: 44, p: prog(t, b(10), b(10) + .6) }); claim('caption', 'text', x, y, w, h); }
  window.LAYOUT = LAYOUT;
}
window.draw = draw; window.FRAMES = FRAMES; window.FPS = FPS;
window.CUES = SHOTS.slice(1).map(s => s.from);                     // cuts, read by render.mjs -> soundtrack and sync-check
// Optional soundtrack: paste skills/soundtrack/templates/groove.js right here, then:
// window.SCORE = ac => buildGroove(ac, { dur: DUR, bpm: BPM, sections: SECTIONS, events: EVENTS });

// live preview when opened directly in a browser (render.mjs loads the page with ?render)
if (!new URLSearchParams(location.search).has('render')) {
  let start = performance.now();
  const loop = () => { draw(Math.floor((performance.now() - start) / 1000 * FPS) % FRAMES); requestAnimationFrame(loop); };
  loop();
  // browsers only allow sound after a user gesture: click restarts from 0 with the score playing
  addEventListener('click', () => { if (!window.SCORE) return; const ac = new AudioContext(); window.SCORE(ac); start = performance.now() + 50; }, { once: true });
}
</script>
</body>
</html>
```

## File: README.md
upstream: https://github.com/iart-ai/javascript-animation-skills/blob/main/README.md

````text
# JavaScript Animation Skills

> Every frame drawn in JavaScript: zero image assets, zero API keys, one HTML file, and the music is synthesized in code too. Agent skills for the kind of animation Claude Opus 5.5 made go around: canvas films in any look, rendered frame-accurately to MP4 and self-checked.

![JavaScript Animation Skills: "I only asked you to fix one line", a 30-second film drawn entirely in code](./showcase.gif)

*"I only asked you to fix one line" ([source](./examples/i-only-asked-you-to-fix-one-line)): an agent turns a one-line typo fix into a new city overnight. No images, no fonts to load, no libraries: one 81 KB HTML file, and every note and sound effect is synthesized by the same file with Web Audio. A second example, ["What a newborn sees"](./examples/what-a-newborn-sees), is a 42-second explainer.*

## Gallery: made by an agent from one prompt

![Three films made by an agent from one prompt each: a cat-vs-vacuum comedy, a toddler's bedtime story, a compound-interest explainer](./examples/gallery/gallery.gif)

Each of these was made by a fresh agent working only from this pack's skill docs and a one-line request, with no human edits: a comedy, a bedtime story for a two-year-old, and a money explainer, each with its own look and its own synthesized soundtrack. [See the gallery](./examples/gallery).

## Install

```bash
npx skills add iart-ai/javascript-animation-skills
```

Or add it as a Claude Code plugin marketplace:

```bash
/plugin marketplace add iart-ai/javascript-animation-skills
```

then `/plugin install javascript-animation-skills`.

The skills run in Claude Code, Cursor, Codex, and 40+ agents. The full agent runs at **[iart.ai](https://www.iart.ai/javascript-animation?utm_source=github&utm_medium=readme&utm_campaign=javascript-animation-skills&utm_content=funnel)**.

## What's included

| Skill | What it does |
|-------|--------------|
| [javascript-animation](./skills/javascript-animation) | Short animated films computed on an HTML canvas: stories, explainers, loops, picture books from your photos. A drawing library (hand-drawn ink, picture-book illustration, spot-color print, single-line engraving, words as shapes, marker fills), a seek-and-render harness to MP4, contact sheets, and a zero-asset audit. |
| [soundtrack](./skills/soundtrack) | Music written in code with Web Audio for each film, living inside the same page and rendered offline to WAV. Two templates (a groove with four instrument kits, a music box) only when you ask for them. A tempo map lands every scene cut on a downbeat, marked by harmony rather than volume. A sync check fails the render if a cut misses the beat or the music jumps loud enough to startle. Also works with AI-generated or your own music. |

## How it works

1. The agent derives a look from the subject (two pieces about different things shouldn't look alike).
2. It writes a **beat grid, a shot list and blocking as data** in the page: tempo, sections (with a break), shots on the beat, for a story one continuous world seen through many cameras, and one event list. Pictures, camera and soundtrack all read that data, so sound lands on every action by construction.
3. Every frame is a pure function of time. A headless browser seeks the page into an MP4; the page's Web Audio score (percussion, bass, pads and a synthesized sound for every action) is rendered offline and muxed in.
4. The agent checks its own work before you see it: zero-asset audit, A/V sync (cuts on the beat, no startling jumps), layout (no text colliding with text or sitting on objects), a still per shot against the storyboard, and a director pass on a 2 fps contact sheet for pace, framing, stillness and a grown-up look.

It only asks you something when it can't reasonably guess. Characters, photo-based likenesses and alternative looks are handled only when your piece calls for them.

## When it activates

- "Draw every frame of this in JavaScript" / "make it with no image assets."
- "Make a hand-drawn animated explainer about ..."
- "Turn these photos into an animated story."
- "Make a short animated film / loop on a canvas."
- "Add music made in code" / "sync the music to the cuts."

## Example prompts

- "Make a 40-second hand-drawn explainer on why babies love black-and-white cards. Every frame in code."
- "Animate a short wordless story about a paper boat on its first rainy day, picture-book style, with a music-box soundtrack."
- "Here are photos of my dog. Make a 30-second animated day-in-the-life of her."

## Not the same as

- [generative-illustration-skills](https://github.com/iart-ai/generative-illustration-skills): AI *generates* the illustration parts and code animates them. This pack generates nothing: every mark is code.

## Which model

Built and tested with **Claude Opus 5.5**. Drawing a whole film in code leans hard on the model: spatial reasoning, taste, and long, careful code. The self-check needs a model that can **look at images** (it reviews its own contact sheets and stills).

Other models have not been tested with this pack. Expect cruder drawings from weaker ones. If your agent lets you pick, use the strongest vision-capable model you have.

## Requirements

Node 18+, `npm i playwright-core`, ffmpeg, and Chrome (or `npx playwright install chromium`). No API keys.

## Topics

`javascript-animation` `canvas` `generative-art` `hand-drawn` `web-audio` `zero-assets` `claude-opus` `claude-skill`

## Inspiration

This pack was prompted by public experiments shared by [@kevin_t_ngo](https://x.com/kevin_t_ngo), [@Voxyz_ai](https://x.com/Voxyz_ai), [@liu8in](https://x.com/liu8in) and [@ann_nnng](https://x.com/ann_nnng). No code or assets from their work are included; the techniques here are general ones, and the example is original.

## More packs

Part of a 19-pack open-source collection: install only what you need. Browse every pack and skill at **[iart.ai/skills](https://www.iart.ai/skills?utm_source=github&utm_medium=readme&utm_campaign=javascript-animation-skills&utm_content=more-packs)**, or the hub at **[github.com/iart-ai/motion-skills](https://github.com/iart-ai/motion-skills)**.

[tiktok-video-skills](https://github.com/iart-ai/tiktok-video-skills) (TikTok / Reels / Shorts creators) · [text-message-video-skills](https://github.com/iart-ai/text-message-video-skills) (Text-message story creators) · [youtube-video-skills](https://github.com/iart-ai/youtube-video-skills) (Podcasters & YouTubers) · [ecommerce-video-skills](https://github.com/iart-ai/ecommerce-video-skills) (E-commerce sellers) · [ad-video-skills](https://github.com/iart-ai/ad-video-skills) (Brand advertisers & marketers) · [data-animation-skills](https://github.com/iart-ai/data-animation-skills) (Analysts & PMs) · [explainer-video-skills](https://github.com/iart-ai/explainer-video-skills) (Educators & content creators) · [map-animation-skills](https://github.com/iart-ai/map-animation-skills) (Vox-style editorial maps) · [web-animation-skills](https://github.com/iart-ai/web-animation-skills) (Frontend developers) · [motion-design-skills](https://github.com/iart-ai/motion-design-skills) (Motion designers) · [kinetic-typography-skills](https://github.com/iart-ai/kinetic-typography-skills) (Kinetic type / text animation) · [freelance-motion-skills](https://github.com/iart-ai/freelance-motion-skills) (Freelancers & studios) · [webgl-animation-skills](https://github.com/iart-ai/webgl-animation-skills) (3D / WebGL / technical) · [manim-skills](https://github.com/iart-ai/manim-skills) (Math / educational animators) · [generative-illustration-skills](https://github.com/iart-ai/generative-illustration-skills) (Generative-illustration & creative coders) · [javascript-animation-skills](https://github.com/iart-ai/javascript-animation-skills) (Every frame drawn in JavaScript) · [lower-thirds-skills](https://github.com/iart-ai/lower-thirds-skills) (Streamers, podcasters & editors) · [b-roll-skills](https://github.com/iart-ai/b-roll-skills) (YouTubers, co
````
