⏳ This skill is pending AI review.
Scores will appear once the review pipeline completes.
line-art-animation
Build animated line-art components in SVG and TypeScript — thin ink lines on paper, people and animals that walk, run, cycle and react, scenes with wind, lit windows and a day/night cycle, exported to video if needed. Use this whenever someone asks for a line art (or ink, pen, doodle, hand-drawn) animation, an animated illustration or scene component, little characters doing everyday things, a living street/village/shop/park, a day-night cycle illustration, "make it like this clip" for a drawn animation, or a video of such a component — even if they never say "SVG" or "line art".
Choose how to use this skill
You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.
1. Native installer
This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.
Do not guess an installer command or replace an existing version without reviewing the diff.
2. Complete package recommended
Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.
No complete ProSkills package is published for this listing yet.3. Prompt-only
Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.
Need only the instruction file?
Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.
No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.
// RATINGS
Not yet listed on ClawHub or SkillsMP
// README
line-art-animation
A Claude skill and a small TypeScript library for animated line-art components: ink-on-paper figures that walk, ride and react, in scenes that run from day to night. Everything is drawn live in SVG, so it stays sharp at any size and responds to the pointer.

| Day | Night |
|---|---|
![]() | ![]() |
What's in the repo
SKILL.md, references/ | The skill: workflow, the rules that make the style work, and guides for style, motion, scenes, verification, matching a reference clip and rendering video. |
lib/ | Four dependency-free TypeScript modules: drawing primitives (ink.ts), a walk/run solver (gait.ts), springs, pendulums and wind (motion.ts), and a time-of-day palette (daynight.ts). |
examples/walker/ | One figure in about 150 lines: a man with a briefcase walks across the card; click him and he tips his hat. |
examples/village/ | A full scene: a street of machiya, a tea house and a bath house by a canal, villagers on schedules, a cat, birds, a boatman, lit windows and reflections, about a dozen interactions. |
scripts/ | Deterministic frame capture for video, and tools for measuring a reference clip. |
Install the skill
For Claude Code, clone it into your skills folder:
git clone https://github.com/JDhruv14/line-art-animation ~/.claude/skills/line-art-animation
or into .claude/skills/ inside a single project. Then ask for what you want, for example:
- "Make a line art animation of a bakery at dawn: a baker carrying trays, steam from the oven, a cat in the window."
- "Turn this clip into a looping line-art component, matching its walk exactly." (attach or link the clip)
- "Add a day-night cycle to the scene and render a 30-second 1080p video."
Claude reads SKILL.md, copies lib/ into your project, shows one figure for approval
before building the rest, and checks motion frame by frame before handing it over.
Run the examples
Requires Node 22.18 or newer.
npm install
npm run dev # http://localhost:5173
In the village, drag the sun or moon across the sky to change the time, move the pointer
to make wind, and click people, windows, lanterns, the wind chime, the cat, the birds or
the water. URL flags: ?start=0.9 sets the starting time (0 is midnight, 0.5 noon),
?tau=0.5 pins it, ?day=30 makes a full day last 30 seconds, ?debug steps time by hand.
npm run typecheck # strict for lib/ and the walker
npm run build
The library in brief

Figures are drawn in their own space, about 95 units tall with feet on y = 120, and placed into a scene with a transform. Limbs are two open pen strokes around a curve through the joints, which is most of what makes the drawing read as hand-inked.
A complete program that draws a pair of legs walking across the page (the walker example adds the body, arms, clothes and the click reaction):
import { el, limb, shoe, place, inkDefs, run } from './lib/ink.ts';
import { gait } from './lib/gait.ts';
const svg = el('svg', { viewBox: '0 0 480 240' });
document.body.append(svg);
const fig = el('g', { filter: inkDefs(svg).filter }, svg);
const legs = [limb(fig, 4.2), limb(fig, 4.2)];
const shoes = [el('path', {}, fig), el('path', {}, fig)];
const walk = gait({ kind: 'walk' });
let phase = 0, x = 60;
run((t, dt) => {
phase += dt / walk.period;
x += walk.speed * 1.25 * dt; // move at the gait's speed and the feet stay planted
place(fig, x % 520 - 20, 196, 1, 1.25);
const p = walk.pose(phase);
p.feet.forEach((foot, i) => {
legs[i].draw([p.hip, foot.knee, foot.ankle]);
shoe(shoes[i], foot.ankle, foot.pitch);
});
});
gait() solves the legs rather than animating them: the planted foot slides back at
exactly the travel speed, the swing follows a minimum-jerk path, the heel peels off the
toe before each step, and hip height comes from what the planted legs can reach, so the
body rises over each step and dips when both feet are down. Clothes are then drawn
around the knees and ankles, so a coat or kimono opens and closes with the stride.
palette(τ) gives sky, paper and ink colours for any time of day. Ink is currentColor
and paper fills carry a pp class, so applyPalette() can turn the whole drawing into
pale ink on indigo at night while windows and lanterns glow.
Render a video
npm run dev
node scripts/capture.ts "http://localhost:5173/examples/village/?debug&capture&day=30&start=0.3" \
captures/village 900 30 1920 1080
ffmpeg -framerate 30 -i captures/village/f%04d.png -c:v libx264 -preset slow -crf 15 \
-pix_fmt yuv420p -movflags +faststart -tune animation village.mp4
The capture script drives headless Chrome over the DevTools protocol, with no npm
dependencies, and advances the scene by exactly one frame between screenshots, so the
result doesn't depend on machine speed. It finds a local Chrome or Chromium, or uses
$CHROME. Needs ffmpeg.
Match a reference clip
node scripts/clip.ts period clip.mp4 X Y W H # loop length of a region
node scripts/clip.ts blobs clip.mp4 X Y W H Y0 Y1 # dark blobs per frame, e.g. feet
scripts/frames.sh clip.mp4 X Y W H out/ # frames with a measuring grid
references/matching.md covers the rest: why to resample by time (most social clips
are variable-frame-rate), reading poses off the grid, and an overlay mode for checking
your drawing against the clip.
License
MIT
// HOW IT'S BUILT
// FILES
37 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.
SKILL.md6.4 KBd75a16e4628bupstream ↗
--- name: line-art-animation description: Build animated line-art components in SVG and TypeScript — thin ink lines on paper, people and animals that walk, run, cycle and react, scenes with wind, lit windows and a day/night cycle, exported to video if needed. Use this whenever someone asks for a line art (or ink, pen, doodle, hand-drawn) animation, an animated illustration or scene component, little characters doing everyday things, a living street/village/shop/park, a day-night cycle illustration, "make it like this clip" for a drawn animation, or a video of such a component — even if they never say "SVG" or "line art". --- # Line-art animation Animated illustration components: everything is drawn with one thin pen on paper, built live in SVG from TypeScript, so it stays crisp at any size, responds to the pointer, and can be stepped frame by frame for checking or video export. This skill ships a small library (`lib/`), two examples (`examples/walker`, a single figure in ~150 lines; `examples/village`, a full scene) and tools (`scripts/`). Read the example that's closest to the request before writing anything. ## How people judge this work They look at it like an animator would: frame by frame, at zoom, against life or against a reference. These were all rejected in practice, and each has a rule below: - walks that bob on a sine wave, feet that slide, gaits sped up to fit a time-lapse - limbs drawn as closed tubes; ruler-straight lines; rigid clothes that ignore the legs - a whole set of components built in one go that all look alike ("AI slop") - interactions that feel like UI instead of the world reacting - a page whose background changes with the scene ("looks like a video, not a component") - reusing characters from a reference clip when asked for something new - leftover props nobody asked for (they asked to remove hanging laundry) ## Workflow 1. **Pin the look** before anything moves. Read `references/style.md`. Decide the pen weight, paper colour, figure proportions and the one or two flat accent colours. 2. **Set up the project.** Copy `lib/` into the project (it's four dependency-free `.ts` files) and use Vite + TypeScript (`package.json`, `tsconfig.json` and `vite.config.ts` in this repo show the setup). Components are plain DOM/SVG — no framework needed. 3. **Build one figure or one corner first** and show it (screenshot or a short clip, next to the reference if there is one). Get a yes before building the rest. A full set built at once comes back as generic; one good piece shows the bar. 4. **Make it move** with `references/motion.md`: `gait()` for walking and running, `spring()` / `pendulum()` for anything attached or hanging, keyed poses with `curve()` or `sequence()` for gestures. Never animate a figure with free sines. 5. **Compose the scene** with `references/scenes.md`: a self-contained card on a fixed page background, layers, a time-of-day palette from `lib/daynight.ts`, lights, wind, people arriving on schedules, interactions that are reactions. 6. **Verify** with `references/verify.md` before showing anything: typecheck, `?debug` stepping, zoomed frame strips of every moving thing, interactions triggered and stepped through, 60 fps in a real tab. 7. **If there's a reference clip to match**, follow `references/matching.md` — measure timing and poses from the clip instead of guessing, and check with an overlay. 8. **If they want a video**, follow `references/video.md` (deterministic headless capture with `scripts/capture.ts`, then ffmpeg). ## Rules that make it work - **Limbs are two open strokes.** `limb()` draws a paper-filled band between two pen lines that stop short of each other at the far end. This is the style's signature. - **Lines curve.** Joints are rounded, edges bow slightly, nothing is ruler-straight. - **Draw each figure in its own space** — ~95 units tall, feet on y = 120, facing +x, standing at x = 40 — and place it with `place(g, x, y, dir, scale)`. Proportions, pen weight and the gait presets all assume this space. - **Clothes are drawn around the skeleton.** Solve the legs (even if hidden), then draw the coat or kimono hem from the forward knee and the ankles so the cloth opens and closes with the stride. Sleeves, scarves and bags swing on springs. - **Feet are planted.** Move a walker by exactly `gait.speed × scale` per second and the stance foot stays still on the ground. Don't speed a gait up to match a compressed clock; compress arrivals instead. - **Ink is `currentColor`, paper is `.pp`.** Retint the whole drawing with `applyPalette()` (day: dark ink on warm paper; night: pale ink on indigo, warm windows). Solid-colour limb fills must use `solid()`, or the paper CSS wins. - **The component is a card.** The page around it never changes colour. - **Interactions are the world reacting**: a person bows or tips a hat, a cat wakes and stretches, a lantern swings, birds scatter, a fish jumps. Pointer movement is wind. No buttons inside the scene; a single faint hint line is enough. - **New means new.** If the brief is "like this but new", keep the medium, pen, proportions and timing feel; invent the characters, activities and props. ## Library at a glance | module | what it gives you | |---|---| | `lib/ink.ts` | `pen` `shape` `blot` `paint` `limb` `solid` `joint` `hang` `curve` `shoe` `place` `toScene` `inkDefs` `run` | | `lib/gait.ts` | `gait({ kind: 'walk' \| 'shuffle' \| 'run', …overrides })` → `{ speed, period, pose(phase, go) }` | | `lib/motion.ts` | `spring` `pendulum` `pointerWind` `sequence` `seeded` `wobble` `ease` `minJerk` … | | `lib/daynight.ts` | `palette(τ)` → sky, paper, ink, `lamp`, `night`, `sunset`; `applyPalette` `nightTint` | `run(draw)` drives everything with `draw(t, dt)`. Two URL flags matter for checking: `?t=1.25` freezes time; `?debug` disables rAF and exposes `window.__step(seconds)` for exact stepping (background and headless tabs throttle rAF, so always verify in debug mode). ## Scripts - `scripts/capture.ts <url?debug> <outDir> <frames> <fps> [w] [h] [setupJs] [frameJs]` — deterministic PNG frames from headless Chrome - `scripts/clip.ts period|blobs …` — loop length of a region; dark-blob tracking per frame - `scripts/frames.sh <clip> x y w h outDir` — grid-overlaid frames for reading poses off a clip All run with Node ≥ 22.18 (TypeScript is stripped natively) plus ffmpeg; `capture.ts` finds a local Chrome/Chromium or uses `$CHROME`.README.md5.6 KB29e8f96b713cupstream ↗
# line-art-animation A Claude skill and a small TypeScript library for animated line-art components: ink-on-paper figures that walk, ride and react, in scenes that run from day to night. Everything is drawn live in SVG, so it stays sharp at any size and responds to the pointer.  | Day | Night | |---|---| |  |  | ## What's in the repo | | | |---|---| | `SKILL.md`, `references/` | The skill: workflow, the rules that make the style work, and guides for style, motion, scenes, verification, matching a reference clip and rendering video. | | `lib/` | Four dependency-free TypeScript modules: drawing primitives (`ink.ts`), a walk/run solver (`gait.ts`), springs, pendulums and wind (`motion.ts`), and a time-of-day palette (`daynight.ts`). | | `examples/walker/` | One figure in about 150 lines: a man with a briefcase walks across the card; click him and he tips his hat. | | `examples/village/` | A full scene: a street of machiya, a tea house and a bath house by a canal, villagers on schedules, a cat, birds, a boatman, lit windows and reflections, about a dozen interactions. | | `scripts/` | Deterministic frame capture for video, and tools for measuring a reference clip. | ## Install the skill For Claude Code, clone it into your skills folder: ```sh git clone https://github.com/JDhruv14/line-art-animation ~/.claude/skills/line-art-animation ``` or into `.claude/skills/` inside a single project. Then ask for what you want, for example: - "Make a line art animation of a bakery at dawn: a baker carrying trays, steam from the oven, a cat in the window." - "Turn this clip into a looping line-art component, matching its walk exactly." (attach or link the clip) - "Add a day-night cycle to the scene and render a 30-second 1080p video." Claude reads `SKILL.md`, copies `lib/` into your project, shows one figure for approval before building the rest, and checks motion frame by frame before handing it over. ## Run the examples Requires Node 22.18 or newer. ```sh npm install npm run dev # http://localhost:5173 ``` In the village, drag the sun or moon across the sky to change the time, move the pointer to make wind, and click people, windows, lanterns, the wind chime, the cat, the birds or the water. URL flags: `?start=0.9` sets the starting time (0 is midnight, 0.5 noon), `?tau=0.5` pins it, `?day=30` makes a full day last 30 seconds, `?debug` steps time by hand. ```sh npm run typecheck # strict for lib/ and the walker npm run build ``` ## The library in brief  Figures are drawn in their own space, about 95 units tall with feet on y = 120, and placed into a scene with a transform. Limbs are two open pen strokes around a curve through the joints, which is most of what makes the drawing read as hand-inked. A complete program that draws a pair of legs walking across the page (the walker example adds the body, arms, clothes and the click reaction): ```ts import { el, limb, shoe, place, inkDefs, run } from './lib/ink.ts'; import { gait } from './lib/gait.ts'; const svg = el('svg', { viewBox: '0 0 480 240' }); document.body.append(svg); const fig = el('g', { filter: inkDefs(svg).filter }, svg); const legs = [limb(fig, 4.2), limb(fig, 4.2)]; const shoes = [el('path', {}, fig), el('path', {}, fig)]; const walk = gait({ kind: 'walk' }); let phase = 0, x = 60; run((t, dt) => { phase += dt / walk.period; x += walk.speed * 1.25 * dt; // move at the gait's speed and the feet stay planted place(fig, x % 520 - 20, 196, 1, 1.25); const p = walk.pose(phase); p.feet.forEach((foot, i) => { legs[i].draw([p.hip, foot.knee, foot.ankle]); shoe(shoes[i], foot.ankle, foot.pitch); }); }); ``` `gait()` solves the legs rather than animating them: the planted foot slides back at exactly the travel speed, the swing follows a minimum-jerk path, the heel peels off the toe before each step, and hip height comes from what the planted legs can reach, so the body rises over each step and dips when both feet are down. Clothes are then drawn around the knees and ankles, so a coat or kimono opens and closes with the stride. `palette(τ)` gives sky, paper and ink colours for any time of day. Ink is `currentColor` and paper fills carry a `pp` class, so `applyPalette()` can turn the whole drawing into pale ink on indigo at night while windows and lanterns glow. ## Render a video ```sh npm run dev node scripts/capture.ts "http://localhost:5173/examples/village/?debug&capture&day=30&start=0.3" \ captures/village 900 30 1920 1080 ffmpeg -framerate 30 -i captures/village/f%04d.png -c:v libx264 -preset slow -crf 15 \ -pix_fmt yuv420p -movflags +faststart -tune animation village.mp4 ``` The capture script drives headless Chrome over the DevTools protocol, with no npm dependencies, and advances the scene by exactly one frame between screenshots, so the result doesn't depend on machine speed. It finds a local Chrome or Chromium, or uses `$CHROME`. Needs ffmpeg. ## Match a reference clip ```sh node scripts/clip.ts period clip.mp4 X Y W H # loop length of a region node scripts/clip.ts blobs clip.mp4 X Y W H Y0 Y1 # dark blobs per frame, e.g. feet scripts/frames.sh clip.mp4 X Y W H out/ # frames with a measuring grid ``` `references/matching.md` covers the rest: why to resample by time (most social clips are variable-frame-rate), reading poses off the grid, and an overlay mode for checking your drawing against the clip. ## License MITscripts/capture.ts5.8 KB4b1a77676d57upstream ↗
// Deterministic frame capture of a page that uses ink.js `run()` with ?debug. // Drives headless Chrome over the DevTools protocol (Node ≥ 22, no npm deps), // advances the scene by exactly 1/fps between screenshots, writes PNGs. // // node scripts/capture.ts <url> <outDir> <frames> <fps> [width] [height] [setupJs] [perFrameJs] // (Node ≥ 22.18 runs .ts directly by stripping types.) // // The url must include ?debug (so the page exposes window.__step). Encode with: // ffmpeg -framerate 30 -i out/f%04d.png -c:v libx264 -preset slow -crf 15 -pix_fmt yuv420p -tune animation out.mp4 // Set CHROME=/path/to/chrome to choose the browser. import { spawn } from 'node:child_process'; import { mkdirSync, writeFileSync, existsSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; const [url, outDir, framesArg, fpsArg, wArg, hArg, setupJs = '', frameJs = ''] = process.argv.slice(2); if (!url || !outDir || !framesArg) { console.error('usage: capture.ts <url> <outDir> <frames> <fps> [w] [h] [setupJs] [perFrameJs]'); process.exit(1); } const FRAMES = +framesArg, FPS = +(fpsArg || 30), W = +(wArg || 1920), H = +(hArg || 1080); function findChrome(): string | undefined { if (process.env.CHROME) return process.env.CHROME; const home = process.env.HOME || ''; const fromCache = (dir: string, test: (d: string) => string): string | null => { if (!existsSync(dir)) return null; for (const d of readdirSync(dir).sort().reverse()) { const p = test(join(dir, d)); if (p && existsSync(p)) return p; } return null; }; return fromCache(join(home, 'Library/Caches/ms-playwright'), (d) => join(d, 'chrome-headless-shell-mac-arm64/chrome-headless-shell')) || fromCache(join(home, 'Library/Caches/ms-playwright'), (d) => join(d, 'chrome-headless-shell-mac-x64/chrome-headless-shell')) || fromCache(join(home, '.cache/ms-playwright'), (d) => join(d, 'chrome-headless-shell-linux64/chrome-headless-shell')) || ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Chromium.app/Contents/MacOS/Chromium', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser'].find(existsSync); } const CHROME = findChrome(); if (!CHROME) { console.error('No Chrome found. Set CHROME=/path/to/chrome (or `npx playwright install chromium-headless-shell`).'); process.exit(1); } mkdirSync(outDir, { recursive: true }); const port = 9400 + Math.floor(Math.random() * 400); const proc = spawn(CHROME, [`--remote-debugging-port=${port}`, '--headless', `--window-size=${W},${H}`, '--hide-scrollbars', '--force-device-scale-factor=1', `--user-data-dir=${join(outDir, '.profile')}`, '--no-first-run', 'about:blank'], { stdio: 'ignore' }); const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); const quit = (code: number): never => { try { proc.kill(); } catch {} return process.exit(code); }; interface Target { type: string; webSocketDebuggerUrl: string } let list: Target[] = []; for (let i = 0; i < 60 && !list.length; i++) { try { list = ((await (await fetch(`http://127.0.0.1:${port}/json/list`)).json()) as Target[]).filter((t) => t.type === 'page'); } catch {} if (!list.length) await sleep(200); } if (!list.length) { console.error('Chrome did not start.'); quit(1); } const ws = new WebSocket(list[0].webSocketDebuggerUrl); await new Promise((r) => (ws.onopen = r)); type Reply = { id?: number; method?: string; params?: any; result?: any; error?: { message: string } }; let id = 0; const pending = new Map<number, (d: Reply) => void>(); const errors: string[] = []; ws.onmessage = (m: MessageEvent<string>) => { const d: Reply = JSON.parse(m.data); if (d.id && pending.has(d.id)) { pending.get(d.id)!(d); pending.delete(d.id); } if (d.method === 'Runtime.exceptionThrown') errors.push(d.params.exceptionDetails.exception?.description || d.params.exceptionDetails.text); if (d.method === 'Runtime.consoleAPICalled' && d.params.type === 'error') errors.push(d.params.args.map((a: { value?: unknown; description?: string }) => a.value ?? a.description).join(' ')); }; const send = (method: string, params: object = {}): Promise<any> => new Promise((res, rej) => { const i = ++id; pending.set(i, (d) => (d.error ? rej(new Error(`${method}: ${d.error.message}`)) : res(d.result))); ws.send(JSON.stringify({ id: i, method, params })); }); const evalJs = async (expression: string): Promise<any> => { const r = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }); if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || r.exceptionDetails.text); return r.result.value; }; await send('Page.enable'); await send('Runtime.enable'); await send('Emulation.setDeviceMetricsOverride', { width: W, height: H, deviceScaleFactor: 1, mobile: false }); await send('Page.navigate', { url }); let ready = false; for (let i = 0; i < 100 && !ready; i++) { await sleep(150); try { ready = await evalJs('typeof __step === "function" && document.readyState === "complete"'); } catch {} } if (!ready) { console.error('Page never exposed __step — is ?debug in the url, and does the page use run()?', errors.join('\n')); quit(1); } await evalJs('document.fonts.ready.then(() => true)'); await sleep(400); if (setupJs) await evalJs(setupJs); const t0 = Date.now(); for (let i = 0; i < FRAMES; i++) { if (i > 0) await evalJs(`__step(${1 / FPS})`); if (frameJs) await evalJs(frameJs); const { data } = (await send('Page.captureScreenshot', { format: 'png' })) as { data: string }; writeFileSync(join(outDir, `f${String(i).padStart(4, '0')}.png`), Buffer.from(data, 'base64')); if (i % 60 === 0) process.stdout.write(`frame ${i}/${FRAMES} ${((Date.now() - t0) / 1000).toFixed(1)}s\n`); } console.log(`done: ${FRAMES} frames in ${((Date.now() - t0) / 1000).toFixed(1)}s`); if (errors.length) { console.error('page errors:\n' + [...new Set(errors)].join('\n')); quit(2); } ws.close(); quit(0);scripts/clip.ts3.5 KBcb3e0d819fdeupstream ↗
// Measure a reference clip. Needs ffmpeg on PATH; run with Node ≥ 22.18. // // node scripts/clip.ts period <clip> <x> <y> <w> <h> [--fps 60] [--min 10] [--max 200] // Loop length of a cropped region: frame-differences it against several // reference frames and prints the best lags in frames and seconds. // // node scripts/clip.ts blobs <clip> <x> <y> <w> <h> <bandY0> <bandY1> [--fps 30] [--dark 110] [--frames N] // Per frame, the x centres (source px) of dark runs inside a horizontal band of // the crop — e.g. ink-dot feet on a ground line. Fit centres, amplitude and // period from this output instead of eyeballing. // // Both resample by time (fps filter), because social-media clips are usually // variable-frame-rate and decoded frame numbers are not a clock. import { execFileSync } from 'node:child_process'; const [mode, clip, ...rest] = process.argv.slice(2); const flags = new Map<string, string>(); const pos: number[] = []; for (let i = 0; i < rest.length; i++) { if (rest[i].startsWith('--')) flags.set(rest[i].slice(2), rest[++i]); else pos.push(Number(rest[i])); } const flag = (k: string, d: number) => (flags.has(k) ? Number(flags.get(k)) : d); function frames(x: number, y: number, w: number, h: number, fps: number): Uint8Array[] { const raw = execFileSync('ffmpeg', ['-v', 'error', '-i', clip, '-vf', `fps=${fps},crop=${w}:${h}:${x}:${y},format=gray`, '-f', 'rawvideo', '-'], { maxBuffer: 1 << 30 }); const n = w * h, out: Uint8Array[] = []; for (let i = 0; i + n <= raw.length; i += n) out.push(raw.subarray(i, i + n)); return out; } if (mode === 'period' && pos.length >= 4) { const [x, y, w, h] = pos; const fps = flag('fps', 60), min = flag('min', 10), max = flag('max', 200); const F = frames(x, y, w, h, fps), N = w * h; const refs: number[] = []; for (let r = 0; r < F.length - max - 1 && refs.length < 12; r += Math.max(1, Math.floor(fps / 6))) refs.push(r); if (!refs.length) refs.push(0); const score = new Map<number, number>(); for (let lag = min; lag < Math.min(max, F.length - 1); lag++) { let s = 0; for (const r of refs) { if (r + lag >= F.length) continue; const A = F[r], B = F[r + lag]; for (let i = 0; i < N; i += 3) s += Math.abs(A[i] - B[i]); } score.set(lag, s); } console.log(`${F.length} frames @ ${fps} fps`); [...score.entries()].sort((a, b) => a[1] - b[1]).slice(0, 8) .forEach(([lag, s]) => console.log(`lag ${String(lag).padStart(4)} frames = ${(lag / fps).toFixed(3)} s score ${s}`)); } else if (mode === 'blobs' && pos.length >= 6) { const [x, y, w, h, y0, y1] = pos; const fps = flag('fps', 30), dark = flag('dark', 110), minPx = flag('min-px', 2), limit = flag('frames', 0); const F = frames(x, y, w, h, fps); const count = limit ? Math.min(limit, F.length) : F.length; for (let i = 0; i < count; i++) { const fr = F[i], runs: number[] = []; const col = Array.from({ length: w }, (_, cx) => { let c = 0; for (let cy = y0; cy <= y1; cy++) if (fr[cy * w + cx] < dark) c++; return c; }); for (let cx = 0; cx < w;) { if (col[cx] >= minPx) { const s = cx; while (cx < w && col[cx] >= minPx) cx++; runs.push(+(x + (s + cx - 1) / 2).toFixed(1)); } else cx++; } console.log(`${String(i).padStart(3)} t=${(i / fps).toFixed(3).padStart(6)} [${runs.join(', ')}]`); } } else { console.error('usage:\n clip.ts period <clip> <x> <y> <w> <h> [--fps 60] [--min 10] [--max 200]\n clip.ts blobs <clip> <x> <y> <w> <h> <bandY0> <bandY1> [--fps 30] [--dark 110] [--frames N]'); process.exit(1); }scripts/frames.sh685 B61ddb2b3c2bdupstream ↗
#!/usr/bin/env bash # Grid frames for reading poses off a clip: # scripts/frames.sh <clip> <x> <y> <w> <h> <outDir> [scale=6] [count=40] # Resamples to 30 fps by time, crops (x,y,w,h) in source px, scales up and draws a # light grid every 5 source px and a red one every 10. outDir/f01.png is t = 0. set -euo pipefail clip=$1 x=$2 y=$3 w=$4 h=$5 out=$6 s=${7:-6} n=${8:-40} mkdir -p "$out" ffmpeg -y -v error -i "$clip" -vf "fps=30,crop=$w:$h:$x:$y,scale=$((w*s)):$((h*s)):flags=neighbor,drawgrid=w=$((5*s)):h=$((5*s)):t=1:[email protected],drawgrid=w=$((10*s)):h=$((10*s)):t=1:[email protected]" -frames:v "$n" "$out/f%02d.png" echo "wrote $n frames to $out (1 source px = $s px, f01 = t 0)"references/matching.md2.5 KB5264fb7825f6upstream ↗
# Matching a reference clip When someone shares an animation and wants it "exactly like this", measure it. Guessed timing and poses were rejected every time; measured ones landed. ## 0. Get the clip and fix the clock For an X post, `https://cdn.syndication.twimg.com/tweet-result?id=<id>&token=4` lists `mediaDetails[].video_info.variants`; take the highest-bitrate mp4. ```sh ffprobe -v error -select_streams v -show_entries stream=r_frame_rate,avg_frame_rate,nb_frames clip.mp4 ``` If `nb_frames / duration` isn't `r_frame_rate`, the clip is variable-frame-rate (most social clips are). Resample by time (`-vf fps=30`) everywhere and index by time. ffmpeg's `trim=start_frame` and `select='…n…'` count decoded frames, and `-f rawvideo` pads to the nominal rate — mixing those once doubled a walk's speed. ## 1. Loop lengths ```sh node scripts/clip.ts period clip.mp4 X Y W H --fps 60 ``` Measure parts separately when they might loop independently: a dog's legs (0.52 s) and its body sway (1.3 s) had different periods. Identical-looking legs also match at half the cycle; use arms or props to tell which lag is the real one. ## 2. Read poses off a grid ```sh scripts/frames.sh clip.mp4 X Y W H out/ 6 40 ``` Every 3 frames (30 fps) over one step, read hip, knees (only when bent), ankles and toe angle in source pixels (`px / scale`). Note the head height for body bob. Rigid parts (coat, head, an arm holding something) are measured once and ride on the hip. Put the numbers into `curve()` keys, or into `gait()` overrides (`stride`, `period`, `duty`, `lift`). ## 3. Track what you can automatically ```sh node scripts/clip.ts blobs clip.mp4 X Y W H BAND_Y0 BAND_Y1 --fps 30 ``` prints dark-run centres per frame, e.g. ink-dot feet in the ground band. Fit centres, amplitudes and the period over the whole clip so nothing drifts by the end. ## 4. Overlay check Add an `?overlay&t=` mode to the page: a `<video>` of the clip positioned so the crop lines up (`width: W_clip / W_crop × 100%`, `left: −X / W_crop × 100%`, `top: −Y / H_crop × 100%`), `currentTime = t` on `loadeddata`, and CSS that turns your ink red at 65 % opacity with paper fills set to `none`. Freeze your drawing at the same `t`. Check 0–0.6 s in 0.1 s steps and a few points late in the clip. ## Copying vs. making new Measuring a clip's motion to match its feel is fine. Shipping its characters as your own is not: if the brief is "like this but new", reuse the medium and timing and draw new characters doing new things.references/motion.md3.9 KBbbccc821ce34upstream ↗
# Motion Animation here is mechanics first: solve where the body has to be, then draw around it. Free-running sines look procedural immediately; every rejected version of a walk had one. ## Walking and running — `gait()` ```ts import { gait } from '../lib/gait.ts'; const walk = gait({ kind: 'walk' }); // or 'shuffle' (kimono, geta), 'run' let phase = 0; // per frame: phase += (dt / walk.period) * go; // go ∈ [0,1] slows to a stop x += dir * walk.speed * SCALE * dt * go; // exactly this speed, or feet slide const p = walk.pose(phase, go); // hip, feet[0..1] {ankle, knee, pitch, stance}, front, bob ``` What it does, so you can extend it rather than replace it: - **Planted foot** slides back under the hip at `stride / (duty × period)` — the travel speed. Move by anything else and feet skate. - **Swing** follows a minimum-jerk curve with a low lift (walk 3.4, geta 2.4); runs add a heel kick and a high, early lift. - **Heel-off**: in the last 14 % of stance the foot pivots on its toe (`pitch`). - **Hip height** is solved, not animated: for a walk, the lowest the planted legs can reach (high at passing, dipped at double support); for a run, compressed over the planted foot and highest in flight. Natural numbers to sanity-check against: adults ≈ 2 steps/s; kimono or geta steps are shorter and lower; children run at ≈ 4 steps/s with a forward lean. Draw from the pose: legs with `limb().draw([hip, knee, ankle])`, the leading leg on top (`p.front`), shoes at `ankle` with `pitch`. Hidden legs (under a kimono or coat) are still solved; the garment is drawn from `p.feet[p.front].knee` and both ankles: - front edge: from the waist, out over the forward knee, down to just past the front ankle - hem: from the front ankle to the rear ankle, so it opens into an A when the legs part - back edge: pushed back only when the rear leg extends behind - a fold line from the rear knee, an overlap line toward the front foot The upper body rides on `p.bob` (with a degree or two of lean), arms swing opposite the legs through springs, sleeves and bags hang on springs/pendulums. ## Things that roll or push - **Wheels** roll without slipping: angle = distance / radius. Cranks turn at a gear ratio of the wheel angle; feet sit on the pedals; legs are IK to the pedals. - **Poling a boat**: plant the pole tip at a fixed world point, let the boat surge while the tip stays put (the pole leans back), lift it out, swing it forward. The boat's speed follows the push, not a constant. ## Things that hang or trail — springs and pendulums ```ts const sleeve = spring(40, 6); // stiffness, damping sleeve.step(-1.4 + Math.sin(stepPhase) * 0.9, dt); // target moves, the sleeve lags const lantern = pendulum(10, 1.1); lantern.step(wind.value * 0.5 + carrierAccel, dt); // force this frame ``` Use them for sleeves, scarves, bags, parasol tilt, lanterns on hooks or sticks, curtains (one pendulum per panel), wind chimes (bell + clapper + paper strip, three coupled pendulums), willow strands, laundry. Drive them with wind, the carrier's acceleration, and clicks (`kick()`). ## Idle life Things should never be perfectly still: breathing (±0.35 units), a tail-tip flick every few seconds, an ear twitch, birds that hop, turn, preen at random intervals (1–4 s), smoke puffs, water strokes drifting, stars twinkling. Randomise intervals, not shapes. ## Gestures and reactions — keyed poses For interactions, key a few poses and blend between them over time (`sequence([['sit', 0.7], ['yawn', 0.9], ['stretch', 1.5], …])`, `curve()` for single channels). Ease each transition. Stop walking before gesturing (blend `go` to 0 over ~0.4 s), then resume. Typical durations: bow 2.6 s, hat tip 1.6 s, cat wake-up 8 s. ## Time compression If a scene runs a day in 30 s, people still walk at natural speed. Compress what can be compressed without looking fake — how often people arrive, the sky, the lights.references/scenes.md3.5 KB2e7711b7236eupstream ↗
# Scenes `examples/village` is the reference implementation of everything here. ## The component - A card (rounded corners, soft shadow, `overflow: hidden`) on a fixed neutral page background (`#ebe8e2`). The page never changes with the scene's time of day. - Any readout (a clock) or hint lives inside the card, coloured with the scene ink. - 2:1 is a good default aspect; size with `width: min(94vw, calc((100vh - 48px) * 2))`. - `touch-action: none` on the card if you use drag interactions. ## Coordinates and layers Pick a scene viewBox (the village uses 960 × 480) and a figure scale (0.5 → figures ≈ 48 tall; a doorway ≈ 60–66; a two-storey house ≈ 140–180). Set the scene pen to pen × figure scale so everything shares one line weight. Layer order, back to front: 1. sky (gradient rect, stars, sun/moon, clouds, far hills in diluted ink at ~40 % opacity) 2. behind-buildings (trees whose canopies rise above roofs, chimneys, wires, birds on wires) 3. buildings 4. street (paper fill), street furniture, a cat on a bench 5. walkers — re-sorted every frame by their ground y 6. foreground (water, a boat, a willow on the near bank) 7. airborne particles (petals) with `pointer-events: none` 8. glow layer: `mix-blend-mode: screen; pointer-events: none` — all light lives here 9. hit areas for small targets Put `inkDefs().filter` on the scene group, not the sky or glow. ## Day and night `palette(τ)` from `lib/daynight.ts`; call `applyPalette(svg, P)` each frame and keep `.pp { fill: var(--paper) }` in CSS. Things that follow time: - **Windows**: a pane drawn before its lattice, filled `mix(paper, warm, lit)`, plus a radial glow. Give each its own on-threshold on `P.lamp` and some an off-time late at night, so lights come on and go out one by one. - **Lanterns, street lamp, bike lamp, boat lantern**: same, with a light cone or flicker. - **Reflections**: horizontal warm strokes in the water under each lit source, jittered. - **Shops** take in their curtains after hours; laundry or stalls follow the day. - **Creatures**: birds roost at dusk, fireflies and moths at night, a cat's eyes glow. - Flat colours go through `nightTint(colour, P)`. Start the live component in the afternoon (τ ≈ 0.66) so a visitor sees dusk within a minute. Let the user drag the sun or moon along its arc to scrub time. ## People and traffic Spawn walkers on per-type timers that depend on the hour (children by day, a lantern instead of a parasol after dark, fewer people deep at night). Start with two or three already on screen so the scene is never empty. Remove them when off-screen. ## Wind `pointerWind(svg)` gives a smoothed value from pointer speed plus a slow breeze. Feed it to everything that hangs or floats — curtains, lanterns, chimes, petals, smoke, willow strands, water strokes, clouds. ## Interactions Every clickable thing reacts in character, takes 1–8 s, and returns to idle by itself: a person bows or tips a hat; a cyclist rings the bell (and the birds scatter); a kid hops; a boatman sings; a cat wakes, yawns, stretches, grooms, curls up; birds flush and resettle; a lantern swings; a chime rings; a window slides open and someone waves; a tree drops petals; the water ripples and a fish jumps; the night sky gets a shooting star. Give small targets a transparent hit path with a `<title>`. Moving characters take `pointerdown` on their own group. ## Performance Create every node once and only update attributes. Keep per-frame work to path strings (`f()` rounds to 2 dp). The village runs ~40 animated objects at 60 fps with the ink filter on.references/style.md3.4 KB877d8f7dce7dupstream ↗
# Style The look in one sentence: one thin, slightly wobbly ink line on warm paper; open, economical figures without faces; flat muted colour used sparingly; buildings drawn straight-on like an elevation. Most of the effort goes into the line, not the colour. ## Pen and paper | | value | why | |---|---|---| | pen | `1.35` figure units (≈1.4 % of a 95-unit figure) | thinner reads as vector, thicker as cartoon | | scene pen | pen × figure scale (0.5 scale → ~0.7–0.8) | architecture and figures must share one pen | | detail pen | 0.4–0.6 × pen | tile lines, slats, hatching, ribs | | ink (day) | `#1c1c1c` | not pure black | | paper (day) | `#fdfcf8` / `#fdfdfc` | warm, never pure white | | caps/joins | round | | | wobble | `inkDefs()` filter: turbulence 0.6, displacement 0.45, blur 0.12 | ink, not vector — keep it subtle | Fills are paper (`shape`) so things occlude each other like a drawing, solid ink (`blot`) for small dark parts, or one flat colour (`paint`) for clothes and props. No gradients on objects; gradients only for sky and light. ## Figures Work in figure space: ~95 units tall, feet on y = 120, facing +x, standing at x = 40. - **Head**: small oval, about 7 × 9 units, faceless. Character comes from hair and hats (bun, cap, bowler, straw hat, kasa), not faces. - **Neck**: short open double stroke. - **Body**: a simple garment silhouette — boxy coat with a straight front, kimono column, striped shirt (`inkDefs().stripes`), solid trousers via `solid()`. - **Limbs**: `limb()` — two open strokes, rounded joints. Legs ~4.2 wide, arms ~3.6. Arm length ≈ 0.44 × height: a hand holding a bag hangs at the thigh, not the waist. - **Feet**: `shoe()` wedges, or drawn geta/tabi; they peel off at the heel. - **Proportions**: head ≈ 1/9.5 of height for adults; children have bigger heads (≈1/6), shorter limbs, and a straw hat or cap helps read age instantly. ## Animals Open strokes only: a back line and a separate belly line, single-stroke legs ending in fat ink-dot feet, a small head with an ear. A cat sitting is a closed paper shape with a few patches; birds are a body oval, a cap blot, a tail line. ## Architecture Draw buildings as street elevations (no perspective), with enough detail that the eye can wander — this is where richness comes from: - tiled roofs: tile channels converging to the ridge, round tile ends along the eave, rafter ends under the fascia, a stacked ridge with end tiles, a slight upward sweep - façades: lattice slats with a rhythm (every fourth slat full height), plaster windows with fat bars, shoji grids, low curved fences, blinds, signboards with real lettering in the right script - props that tell you who lives there: barrels, pots, a bench, buckets, a bicycle Keep large areas of plain paper. Density belongs on the buildings, not the sky. ## Colour Pick one or two accents and use them in small areas (a red parasol and lanterns, an indigo kimono, yellow pails). At night every flat colour is pushed toward the night palette with `nightTint()`, and ink becomes pale — see `scenes.md`. ## Day and night Day: dark ink on warm paper, soft gradient sky. Night: the drawing inverts — pale ink on indigo paper — and light comes from the windows, lanterns, a street lamp, a bike lamp, fireflies, each with a warm radial glow on a `mix-blend-mode: screen` layer. The moon is a pale crescent, stars twinkle. This inversion is why ink is `currentColor`.references/verify.md2.6 KBbd2c91a25dfdupstream ↗
# Verifying Check what the person will check — motion frame by frame and detail at zoom — before showing them anything. ## 1. Types and build ```sh npm run typecheck # tsc, strict for lib/ and small examples npm run build # vite build ``` ## 2. Step time exactly Load the page with `?debug`. `run()` then skips rAF and exposes `window.__step(s)`, which advances in exact 1/60 s steps. Background tabs, embedded preview panes and headless browsers throttle rAF to a frame or two per second, which makes everything crawl and can make a working scene look broken — always check in debug mode. `?t=1.25` freezes a normal page at one moment. ## 3. Look at frames, not screenshots of the whole card Pane screenshots are too downscaled to judge a 1-unit pen. Either temporarily widen the SVG container 4–11× and pan it over the area, or capture headless and crop: ```sh node scripts/capture.ts "http://localhost:5173/examples/walker/?debug" /tmp/w 8 8 1920 1080 ffmpeg -i /tmp/w/f%04d.png -vf "crop=560:500:330:330,scale=280:-1,tile=8x1" -frames:v 1 -update 1 strip.png ``` To follow a moving figure, pass setup and per-frame JS to `capture.ts` that pick the figure and re-centre a zoomed container on it, so one stride reads in place: ```sh SETUP='window.K = __village.people[0]; true' FRAME='(() => { const v = document.querySelector("#village"), z = 11; v.style.cssText = `width:${960*z}px;height:${480*z}px;position:fixed;left:${-(K.x-22)*z}px;top:${-(K.y-58)*z}px`; return true })()' node scripts/capture.ts "http://localhost:5173/examples/village/?debug&tau=0.5" /tmp/g 9 8 480 640 "$SETUP" "$FRAME" ``` Expose whatever handles you need on `window` in the example (the village exposes `__village` with its people, cat, boat and spawn function). What to look for in a strip: - feet stay still while planted; no skating, no popping between frames - the body rises over the planted foot and dips at double support (walk) - clothing opens and closes with the stride; sleeves and bags lag, then settle - the leading leg is drawn on top - nothing is ruler-straight; limbs are open at the ends - props sit where hands are; a held bag hangs at the thigh ## 4. Trigger every interaction Dispatch `pointerdown` on each hit area (`<title>` names them) and step through the reaction, taking frames at the start, middle and end. Check it returns to idle. ## 5. Sweep the day Render at τ = 0.3, 0.5, 0.72, 0.75, 0.8, 0.95, 0.24: day, golden hour, sunset, the ink flip, night, late night (lights going out), dawn. Contrast must hold everywhere except the brief flip. ## 6. Real frame rate In a foreground tab, count rAF callbacks for 3 s; expect ~60.references/video.md1.5 KB79cf556fd82dupstream ↗
# Rendering to video Capture is deterministic: the page runs in `?debug` mode and `scripts/capture.ts` advances it by exactly 1/fps between screenshots, so motion is right regardless of machine speed. ```sh npm run dev # or any server for the built files node scripts/capture.ts "http://localhost:5173/examples/village/?debug&capture&day=30&start=0.3" \ captures/village 900 30 1920 1080 ffmpeg -framerate 30 -i captures/village/f%04d.png \ -c:v libx264 -preset slow -crf 15 -pix_fmt yuv420p -movflags +faststart -tune animation village.mp4 ``` - 1080p at 30 fps for 30 s is 900 frames, about 90 s to capture. - Use page flags rather than code edits: the village supports `capture` (hides the hint), `day=<seconds>` (length of a full day), `start=<τ>` (starting time, keeps running) and `tau=<τ>` (pins the time). - A full day in 30 s from τ = 0.3 shows morning → noon → sunset → night → dawn. - Render the component in its card on the page background, so the video shows it as a component. - Check a contact sheet before sending: `ffmpeg -i out.mp4 -vf "fps=1/3.75,scale=480:-1,tile=4x2" -frames:v 1 sheet.png`. - For a README or post, a short GIF: `ffmpeg -i out.mp4 -vf "fps=15,scale=800:-1:flags=lanczos,split[a][b];[a]palettegen[p];[b][p]paletteuse" out.gif`. `capture.ts` uses `$CHROME`, a Playwright Chromium in the user cache, or a system Chrome/Chromium; it exits non-zero and prints page errors if the page threw..gitignore46 B37c3eab954f1upstream ↗
node_modules/ dist/ .DS_Store *.log captures/examples/village/canal.ts10 KBbf7fe1ac29e3upstream ↗
// Street surface, canal wall, water, reflections, willow, koi, fireflies. import { el, pen, shape, blot, f, pt, PAPER } from '../../lib/ink.ts'; import { W, H, BASE, EDGE, WATER, SP, rnd, srnd, clamp, lerp, smooth, ease, oval, rgb, hex, mix, wobble } from './kit.ts'; const WARM = hex('#ffcf7e'); export function buildCanal({ ground, canalL, willowL, glow }, defs) { // ---------- street surface and gutter el('path', { d: `M-10 ${BASE} L${W + 10} ${BASE} L${W + 10} ${EDGE} L-10 ${EDGE}Z`, fill: PAPER }, ground); // ---------- canal wall: coping stones then two courses of masonry const wall = el('g', {}, canalL); shape(wall, SP).setAttribute('d', `M-10 ${EDGE} L${W + 10} ${EDGE} L${W + 10} ${WATER} L-10 ${WATER}Z`); const d = [`M-10 ${EDGE + 5} L${W + 10} ${EDGE + 5}`, `M-10 ${EDGE + 10.5} Q${W / 2} ${EDGE + 10} ${W + 10} ${EDGE + 10.6}`]; for (let x = srnd(0, 20); x < W; x += srnd(28, 44)) d.push(`M${f(x)} ${EDGE} l0.4 5`); [[EDGE + 5, EDGE + 10.5, 0], [EDGE + 10.5, WATER, 8]].forEach(([y0, y1, o]) => { for (let x = srnd(0, 14) + o; x < W; x += srnd(12, 24)) d.push(`M${f(x)} ${f(y0 + 0.4)} Q${f(x + srnd(-1, 1))} ${f((y0 + y1) / 2)} ${f(x + srnd(-0.6, 0.6))} ${f(y1 - 0.4)}`); }); for (let i = 0; i < 40; i++) { const x = srnd(4, W - 4), y = srnd(EDGE + 6, WATER - 2); d.push(`M${f(x)} ${f(y)} l${f(srnd(1, 2.6))} ${f(srnd(-0.3, 0.3))}`); } pen(wall, SP * 0.5).setAttribute('d', d.join(' ')); // moss tufts hanging over the coping const moss = []; for (let i = 0; i < 26; i++) { const x = srnd(0, W); moss.push(`M${f(x)} ${EDGE + 5} q-1 3 0.4 5 M${f(x + 2)} ${EDGE + 5} q1 2.6 -0.2 4.4`); } pen(wall, SP * 0.45).setAttribute('d', moss.join(' ')); // ---------- water const water = el('path', { d: `M-10 ${WATER} L${W + 10} ${WATER} L${W + 10} ${H + 10} L-10 ${H + 10}Z` }, canalL); pen(canalL, SP * 0.8).setAttribute('d', `M-10 ${WATER} L${W + 10} ${WATER}`); const reflG = el('g', {}, canalL); const ripG = el('g', {}, canalL); const lines = Array.from({ length: 46 }, (_, i) => ({ x: rnd(-40, W), y: WATER + 5 + (i % 9) * 8.4 + rnd(-2, 2), len: rnd(10, 34), v: rnd(4, 9), n: pen(ripG, SP * 0.5) })); const rings = []; const ringG = el('g', {}, canalL); const ring = (x, y, n = 1, big = 1) => { for (let i = 0; i < n; i++) rings.push({ x, y, t: -i * 0.22, big, n: el('ellipse', { fill: 'none', stroke: 'currentColor', 'stroke-width': SP * 0.55 }, ringG) }); }; // reflections: light streaks under each lit source const refl = []; const addRefl = (src, x, w, warm = true) => { const strokes = Array.from({ length: 9 }, (_, k) => el('path', { stroke: warm ? '#ffcf7e' : '#f3ecd6', 'stroke-width': 1.4 - k * 0.08, 'stroke-linecap': 'round', fill: 'none' }, reflG)); refl.push({ src, x, w, strokes, warm }); }; // floating petals land here const floating = []; const floatG = el('g', {}, canalL); // ---------- koi (jumps where you click, or now and then) const koiG = el('g', { opacity: 0 }, canalL); const koiBody = el('path', { fill: '#f4ede0', stroke: 'currentColor', 'stroke-width': SP * 0.8 }, koiG); const koiSpots = el('path', { fill: '#d4552f' }, koiG); const koiFin = shape(koiG, SP * 0.6), koiEye = el('circle', { r: 0.9, fill: 'currentColor' }, koiG); let koi = null; const jump = (x) => { if (koi) return; koi = { x: clamp(x, 60, W - 60), t: 0, dir: Math.random() < 0.5 ? -1 : 1 }; ring(koi.x, WATER + 14, 2); }; // ---------- weeping willow on the near bank (left) const willow = el('g', {}, willowL); shape(willow, SP).setAttribute('d', 'M14 384 Q20 340 16 300 Q12 262 34 236 Q46 222 40 206 L46 206 Q54 226 42 244 Q24 270 28 306 Q32 344 28 384Z'); pen(willow, SP * 0.8).setAttribute('d', 'M36 238 Q66 214 104 212 M30 260 Q60 246 86 252 M40 222 Q22 204 -4 202 M42 214 Q56 196 82 190'); pen(willow, SP * 0.45).setAttribute('d', 'M20 330 q3 -6 0 -12 M24 290 q-3 -6 1 -12 M18 360 q2 -4 -1 -8'); const strands = []; const roots = [[104, 212], [86, 252], [-4, 202], [82, 190], [64, 216], [52, 252], [20, 206], [70, 196], [94, 230], [40, 226], [6, 214]]; roots.forEach(([rx, ry], i) => { const n = 4; for (let k = 0; k < n; k++) { const x = rx + srnd(-10, 10), y = ry + srnd(-3, 5), len = srnd(80, 150); strands.push({ x, y, len, ph: srnd(0, 6), stiff: srnd(0.7, 1.3), n: pen(willow, SP * 0.5), leaves: pen(willow, SP * 0.45), a: 0, v: 0 }); } }); let willowKick = 0; // ---------- fireflies (night) and moths at the street lamp const flies = Array.from({ length: 22 }, (_, i) => ({ cx: srnd(20, W - 20), cy: srnd(300, 460), ph: srnd(0, 50), sp: srnd(0.4, 0.9), blink: srnd(2, 5), n: el('circle', { r: 5.5, fill: 'url(#v-fly)' }, glow), dot: el('circle', { r: 0.9, fill: '#f1ffb4' }, glow) })); const fly = el('radialGradient', { id: 'v-fly' }, defs); el('stop', { offset: 0, 'stop-color': '#e9ff9a', 'stop-opacity': 0.9 }, fly); el('stop', { offset: 1, 'stop-color': '#c8ff6a', 'stop-opacity': 0 }, fly); const moths = Array.from({ length: 4 }, () => ({ ph: rnd(0, 6), r: rnd(5, 12), sp: rnd(3, 6), n: el('circle', { r: 0.7, fill: '#fff4d2' }, glow) })); return { ring, jump, addRefl, floatPetal(p) { floating.push({ x: p.x, y: WATER + rnd(3, 40), r: p.r, life: 0, n: el('ellipse', { rx: 1.5, ry: 0.7, fill: '#f6dfe4', stroke: 'currentColor', 'stroke-width': SP * 0.4 }, floatG) }); }, poke(x, y) { if (y > WATER) { if (Math.random() < 0.7 || !koi) jump(x); ring(x, y, 3); } }, willowPoke() { willowKick = 1; strands.forEach((s) => (s.v += rnd(1.5, 3))); }, draw(t, dt, P, wind, lights, tau, lampOn, moonX?: number) { water.setAttribute('fill', rgb(mix(P.paper, P.inkT > 0.5 ? hex('#0f1730') : hex('#bfd0d8'), P.inkT > 0.5 ? 0.45 : 0.32))); lines.forEach((l) => { l.x += (l.v + wind * 4) * dt; if (l.x > W + 20) l.x = -40; if (l.x < -50) l.x = W + 10; const y = l.y + Math.sin(t * 1.3 + l.x * 0.04) * 0.7; l.n.setAttribute('d', `M${f(l.x)} ${f(y)} Q${f(l.x + l.len / 2)} ${f(y - 1.2)} ${f(l.x + l.len)} ${f(y)}`); }); if (Math.random() < dt * 0.5) ring(rnd(40, W - 40), rnd(WATER + 10, H - 10), 1, 0.6); if (P.night < 0.5 && Math.random() < dt * 0.03) jump(rnd(120, W - 120)); for (let i = rings.length - 1; i >= 0; i--) { const r = rings[i]; r.t += dt; if (r.t < 0) { r.n.setAttribute('opacity', 0); continue; } r.n.setAttribute('cx', f(r.x)); r.n.setAttribute('cy', f(r.y)); r.n.setAttribute('rx', f((2 + r.t * 12) * r.big)); r.n.setAttribute('ry', f((0.6 + r.t * 2.2) * r.big)); r.n.setAttribute('opacity', f(Math.max(0, 1 - r.t / 1.6))); if (r.t > 1.6) { r.n.remove(); rings.splice(i, 1); } } // reflections refl.forEach((r) => { const lit = r.src(); r.strokes.forEach((s, k) => { if (lit < 0.02) { s.setAttribute('d', ''); return; } const y = WATER + 6 + k * 6.5, jit = Math.sin(t * 2.2 + k * 1.7 + r.x * 0.1) * (2 + k * 0.5); const w = r.w * (1 - k * 0.07) * (0.7 + 0.3 * Math.sin(t * 1.7 + k)); s.setAttribute('d', `M${f(r.x - w / 2 + jit)} ${f(y)} L${f(r.x + w / 2 + jit)} ${f(y)}`); s.setAttribute('opacity', f(lit * (0.75 - k * 0.07))); }); }); // floating petals drift downstream for (let i = floating.length - 1; i >= 0; i--) { const p = floating[i]; p.life += dt; p.x += (6 + wind * 3) * dt; p.r += dt * 0.3; p.n.setAttribute('cx', f(p.x)); p.n.setAttribute('cy', f(p.y + Math.sin(t + p.x * 0.05) * 0.6)); p.n.setAttribute('transform', `rotate(${f(p.r * 40)} ${f(p.x)} ${f(p.y)})`); p.n.setAttribute('opacity', f(Math.min(1, (12 - p.life) / 2))); if (p.life > 12 || p.x > W + 10) { p.n.remove(); floating.splice(i, 1); } } // koi leap: arc out of the water, flip, splash back in if (koi) { koi.t += dt; const u = koi.t / 1.1; if (u >= 1) { ring(koi.x + koi.dir * 30, WATER + 14, 3, 1.2); koi = null; koiG.setAttribute('opacity', 0); } else { const x = koi.x + koi.dir * 30 * u, y = WATER + 14 - 26 * Math.sin(Math.PI * u); const ang = Math.atan2(-26 * Math.PI * Math.cos(Math.PI * u), 30) * 57.3; const bend = Math.sin(u * 18) * 2; koiG.setAttribute('opacity', 1); koiG.setAttribute("transform", `translate(${f(x)} ${f(y)}) rotate(${f(ang * koi.dir)}) scale(${koi.dir} 1)`); koiBody.setAttribute('d', `M-11 0 Q-4 -5.4 6 -3.6 Q11 -2 12 0 Q11 2 6 3.6 Q-4 5.4 -11 0Z M-11 0 L-17 ${f(-4.5 + bend)} Q-15 0 -17 ${f(4.5 + bend)}Z`); koiSpots.setAttribute('d', `${oval(2, -1.5, 3.2, 1.8)} ${oval(-5, 1, 2.6, 1.6)} ${oval(8.6, -0.8, 1.6, 1.2)}`); koiFin.setAttribute('d', `M-1 3 L-4 7.5 L2 4Z`); koiEye.setAttribute('cx', 9); koiEye.setAttribute('cy', -0.8); if (u > 0.08 && u < 0.12 && !koi.dripped) { koi.dripped = true; ring(koi.x, WATER + 12, 2, 0.9); } } } // willow strands: pendulums driven by the wind willowKick = Math.max(0, willowKick - dt); strands.forEach((s) => { s.v += (-s.a * 3.2 * s.stiff + wind * 0.32 + wobble(t * 0.6 + s.ph) * 0.12 - s.v * 0.9) * dt; s.a += s.v * dt; const pts = []; for (let k = 0; k <= 10; k++) { const u = k / 10, sway = s.a * s.len * u * u * 0.9 + Math.sin(t * 1.6 + s.ph + u * 3) * 1.2 * u; pts.push([s.x + sway + u * 2, s.y + s.len * u - Math.abs(s.a) * s.len * u * u * 0.12]); } s.n.setAttribute('d', 'M' + pts.map(pt).join('L')); s.leaves.setAttribute('d', pts.slice(2).map(([x, y], k) => `M${f(x)} ${f(y)} l${k % 2 ? 2 : -2} 2.4`).join(' ')); }); // fireflies: drift on slow noise, blink, only after dark flies.forEach((fl, i) => { const tt = t * fl.sp + fl.ph; const x = fl.cx + Math.sin(tt * 0.7) * 30 + Math.sin(tt * 1.9) * 8, y = fl.cy + Math.sin(tt * 0.9 + 1) * 16 + Math.cos(tt * 2.3) * 5; const b = Math.pow(Math.max(0, Math.sin(t * fl.blink + fl.ph)), 3); fl.n.setAttribute('cx', f(x)); fl.n.setAttribute('cy', f(y)); fl.dot.setAttribute('cx', f(x)); fl.dot.setAttribute('cy', f(y)); fl.n.setAttribute('opacity', f(P.night * b)); fl.dot.setAttribute('opacity', f(P.night * (0.3 + 0.7 * b))); }); moths.forEach((m, i) => { const a = t * m.sp + m.ph, x = 446 + Math.cos(a) * m.r + Math.sin(a * 2.7) * 3, y = 240 + Math.sin(a * 1.3) * m.r * 0.6; m.n.setAttribute('cx', f(x)); m.n.setAttribute('cy', f(y)); m.n.setAttribute('opacity', f(lampOn * (0.6 + 0.4 * Math.sin(a * 5)))); }); }, }; }examples/village/critters.ts15 KB14967a093946upstream ↗
// Cat, sparrows, swallows, cherry petals, chimney smoke. import { el, pen, shape, blot, f, pt, PAPER } from '../../lib/ink.ts'; import { W, BASE, EDGE, WATER, SP, rnd, pick, clamp, lerp, smooth, ease, oval, rgb, hex, mix, wobble } from './kit.ts'; const L2 = (a, b, t) => [lerp(a[0], b[0], t), lerp(a[1], b[1], t)]; // ===================================================================== calico cat on the bench // Pose = a handful of points; the cat blends between keyed poses. const POSES = { sleep: { S: [-7, -6.4], H: [7, -6.6], Bc: [0, -9.4], C: [-9, -0.2], Bt: [9.6, -0.2], hd: [-10.6, -3.6], tilt: 30, ear: 0.4, eye: 0, mouth: 0, F1: [-11, 0], F2: [-8.6, 0], T0: [9, -2], T1: [6, 3], T2: [-5, 1.2], paw: 0 }, sit: { S: [-4.4, -12.6], H: [4.6, -5.4], Bc: [2.2, -11.4], C: [-6.4, -1.4], Bt: [6.6, -0.2], hd: [-5.4, -17.6], tilt: 0, ear: 1, eye: 1, mouth: 0, F1: [-5.6, 0], F2: [-3.4, 0], T0: [6.6, -1], T1: [13, 0.6], T2: [15.6, -4.4], paw: 0 }, yawn: { S: [-4.4, -12.8], H: [4.6, -5.4], Bc: [2.2, -11.6], C: [-6.4, -1.4], Bt: [6.6, -0.2], hd: [-5.6, -18.6], tilt: -18, ear: 0.6, eye: 0, mouth: 1, F1: [-5.6, 0], F2: [-3.4, 0], T0: [6.6, -1], T1: [13, 0.6], T2: [15.6, -4.4], paw: 0 }, stretch: { S: [-9.4, -4.6], H: [5.4, -11.6], Bc: [-1, -8.6], C: [-11, -1], Bt: [7.4, -3.6], hd: [-15.6, -6.6], tilt: -6, ear: 0.7, eye: 0.3, mouth: 0, F1: [-17.6, 0], F2: [-15, 0], T0: [7, -9.6], T1: [10, -17], T2: [8.6, -22], paw: 0 }, groom: { S: [-4.4, -12.6], H: [4.6, -5.4], Bc: [2.2, -11.4], C: [-6.4, -1.4], Bt: [6.6, -0.2], hd: [-5.2, -16.4], tilt: 22, ear: 1, eye: 0, mouth: 0, F1: [-5.6, 0], F2: [-6.6, -13.6], T0: [6.6, -1], T1: [13, 0.6], T2: [15.6, -3.4], paw: 1 }, }; const lerpPose = (a, b, t) => { const o = {}; for (const k in a) o[k] = Array.isArray(a[k]) ? L2(a[k], b[k], t) : lerp(a[k], b[k], t); return o; }; const SEQ: Array<[string, number]> = [['sit', 0.7], ['yawn', 0.9], ['sit', 0.4], ['stretch', 1.5], ['sit', 0.6], ['groom', 0.45], ['sit', 0.35], ['groom', 0.45], ['sit', 0.35], ['groom', 0.45], ['sit', 0.9], ['sleep', 1.1]]; export function createCat(parent, glow, { x, y }) { const g = el('g', { style: 'cursor:pointer' }, parent); const tailOut = el('path', { fill: 'none', stroke: 'currentColor', 'stroke-width': 3.1, 'stroke-linecap': 'round' }, g); const tailIn = el('path', { fill: 'none', stroke: '#d08a4a', 'stroke-width': 1.5, 'stroke-linecap': 'round' }, g); const legs = pen(g, SP * 1.6); const body = shape(g, SP); const patch = el('path', { fill: '#d08a4a' }, g), patch2 = blot(g); const paws = shape(g, SP * 0.7); const headG = el('g', {}, g); const ears = el('path', { fill: PAPER, stroke: 'currentColor', 'stroke-width': SP * 0.9, 'stroke-linejoin': 'round' }, headG); el('ellipse', { cx: 0, cy: 0, rx: 4.6, ry: 4.1, fill: PAPER, stroke: 'currentColor', 'stroke-width': SP }, headG); const capPatch = blot(headG); const face = pen(headG, SP * 0.6); const mouth = el('path', { fill: '#6a2a2a', stroke: 'currentColor', 'stroke-width': SP * 0.5 }, headG); const eyesGlow = [0, 1].map(() => el('circle', { r: 2.4, fill: 'url(#v-cateye)', opacity: 0 }, glow)); let seqT = -1, idle = 0, flick = 0, ear = 0; const hit = el('rect', { x: x - 20, y: y - 26, width: 42, height: 28, fill: 'transparent' }, g); return { g, hit, poke() { if (seqT < 0) seqT = 0; }, draw(t, dt, P) { // which pose now? const awakeAtNight = P.night > 0.55; let pose; if (seqT >= 0) { seqT += dt; let acc = 0, prev = awakeAtNight ? 'sit' : 'sleep', cur = SEQ[0][0], u = 1; for (let i = 0; i < SEQ.length; i++) { const [name, d] = SEQ[i]; if (seqT < acc + d) { cur = name; u = (seqT - acc) / d; break; } acc += d; prev = name; cur = name; } if (seqT > SEQ.reduce((a, s) => a + s[1], 0)) seqT = -1; pose = lerpPose(POSES[prev], POSES[cur], ease(Math.min(1, u * 1.6))); } else pose = lerpPose(POSES.sleep, POSES.sit, ease(clamp((P.night - 0.4) * 4, 0, 1))); // breathing, tail tip flick, ear twitch const breathe = Math.sin(t * 1.8) * 0.35; idle -= dt; if (idle < 0) { idle = rnd(2, 6); if (Math.random() < 0.6) flick = 1; else ear = 1; } flick = Math.max(0, flick - dt * 1.6); ear = Math.max(0, ear - dt * 3); const X = (p) => x + p[0], Y = (p) => y + p[1]; const S = [X(pose.S), Y(pose.S) - breathe], H = [X(pose.H), Y(pose.H) - breathe * 0.6], Bc = [X(pose.Bc), Y(pose.Bc) - breathe * 1.2]; const C = [X(pose.C), Y(pose.C)], Bt = [X(pose.Bt), Y(pose.Bt)]; body.setAttribute('d', `M${pt(C)} Q${f(C[0] - 2)} ${f((C[1] + S[1]) / 2)} ${pt(S)} Q${pt(Bc)} ${pt(H)} Q${f(H[0] + 4)} ${f((H[1] + Bt[1]) / 2)} ${pt(Bt)} Q${f((Bt[0] + C[0]) / 2)} ${f(Math.max(Bt[1], C[1]) + 1)} ${pt(C)}Z`); const mid = L2(S, H, 0.55); patch.setAttribute('d', `M${f(mid[0] - 3.4)} ${f(mid[1] + 0.6)} Q${f(mid[0])} ${f(mid[1] - 3)} ${f(mid[0] + 4)} ${f(mid[1] + 0.2)} Q${f(mid[0] + 1)} ${f(mid[1] + 3.6)} ${f(mid[0] - 3.4)} ${f(mid[1] + 0.6)}Z`); patch.setAttribute('fill', rgb(mix(hex('#d08a4a'), hex('#5a3a28'), P.inkT * 0.6))); tailIn.setAttribute('stroke', rgb(mix(hex('#d08a4a'), hex('#5a3a28'), P.inkT * 0.6))); const hb = L2(S, H, 0.85); patch2.setAttribute('d', oval(hb[0], hb[1] + 1.4, 1.8, 1.2)); const fl = Math.sin(t * 14) * 2.5 * flick; const T0 = [X(pose.T0), Y(pose.T0)], T1 = [X(pose.T1), Y(pose.T1)], T2 = [X(pose.T2) + fl, Y(pose.T2) - fl * 0.4]; tailOut.setAttribute('d', `M${pt(T0)} Q${pt(T1)} ${pt(T2)}`); tailIn.setAttribute('d', `M${pt(T0)} Q${pt(T1)} ${pt(T2)}`); const sh = [S[0] + 1.4, S[1] + 4]; const F1 = [X(pose.F1), Y(pose.F1)], F2 = [X(pose.F2), Y(pose.F2)]; legs.setAttribute('d', `M${pt(sh)} L${pt(F1)} M${f(sh[0] + 1.6)} ${f(sh[1])} L${pt(F2)}`); paws.setAttribute('d', `${oval(F1[0] - 0.4, F1[1] - 0.6, 1.5, 0.9)} ${oval(F2[0] - 0.4, F2[1] - 0.6, 1.5, 0.9)}`); // head const hd = [X(pose.hd), Y(pose.hd) - breathe]; headG.setAttribute('transform', `translate(${pt(hd)}) rotate(${f(pose.tilt)})`); const e = pose.ear, tw = ear * 0.6; ears.setAttribute('d', `M-4 -2 L${f(-4.2 - (1 - e) * 1.4)} ${f(-7.4 + (1 - e) * 3 + tw)} L-1 -3.6Z M1.4 -3.8 L${f(3.6 + (1 - e) * 1.6)} ${f(-7.2 + (1 - e) * 3)} L4.4 -1.8Z`); capPatch.setAttribute('d', 'M-4.4 -1.2 Q-3.6 -3.8 -0.6 -4 Q-1.6 -1.6 -4.4 -1.2Z'); const open = pose.eye; face.setAttribute('d', (open > 0.5 ? 'M-2.6 -0.4 a0.6 0.8 0 1 0 0.1 0 M1 -0.4 a0.6 0.8 0 1 0 0.1 0' : 'M-3.2 -0.2 q0.7 0.7 1.4 0 M0.6 -0.2 q0.7 0.7 1.4 0') + ' M-1.2 1.4 l0.6 0.5 l0.6 -0.5 M-4.4 1.6 l-3.6 -0.4 M-4.4 2.4 l-3.4 0.8 M2.6 1.8 l3.4 -0.2'); mouth.setAttribute('d', pose.mouth > 0.1 ? oval(-0.6, 2.6, 1.2 * pose.mouth, 1.5 * pose.mouth) : ''); eyesGlow.forEach((n, i) => { n.setAttribute('cx', f(hd[0] - 2.2 + i * 3.6)); n.setAttribute('cy', f(hd[1] - 0.4)); n.setAttribute('opacity', f(P.night * (open > 0.5 ? 0.9 : 0))); }); }, }; } // ===================================================================== sparrows on the wire export function createSparrows(parent, { wireY, count = 7 }) { const g = el('g', {}, parent); const spots = [540, 575, 610, 660, 720, 790, 850, 905]; const birds = Array.from({ length: count }, (_, i) => { const bg = el('g', {}, g); return { x: spots[i] + rnd(-6, 6), dir: Math.random() < 0.5 ? -1 : 1, state: 'perch', t: 0, next: rnd(1, 5), hopT: -1, tail: 0, peck: 0, g: bg, tailN: pen(bg, SP * 0.9), body: shape(bg, SP * 0.7), cap: el('path', { fill: '#7a5a3c' }, bg), cheek: blot(bg), beak: blot(bg), wing: pen(bg, SP * 0.5), legs: pen(bg, SP * 0.4), wings: pen(bg, SP * 0.8), fx: 0, fy: 0, path: null, hopFrom: 0, hopTo: 0, }; }); const hit = el('path', { fill: 'transparent', style: 'cursor:pointer', d: '' }, g); const flush = () => birds.forEach((b) => { if (b.state === 'perch') takeOff(b, false); }); function takeOff(b, away) { const y0 = wireY(b.x) - 2.5; const nx = away ? (Math.random() < 0.5 ? -40 : 1000) : clamp(spots[(Math.random() * spots.length) | 0] + rnd(-8, 8), 520, 930); const up = rnd(40, 80); b.path = { p0: [b.x, y0], c1: [b.x + rnd(-80, 80), y0 - up], c2: [nx + rnd(-60, 60), y0 - up * rnd(0.6, 1.2)], p1: [nx, away ? rnd(20, 80) : wireY(nx) - 2.5], dur: rnd(1.8, 3.2), away }; b.state = 'fly'; b.t = 0; } const bez = (p, u) => { const a = 1 - u; return [0, 1].map((k) => a * a * a * p.p0[k] + 3 * a * a * u * p.c1[k] + 3 * a * u * u * p.c2[k] + u * u * u * p.p1[k]); }; return { g, hit, flush, draw(t, dt, P) { const roost = P.night > 0.5; hit.setAttribute('d', `M520 ${wireY(520) - 14} L940 ${wireY(940) - 14} L940 ${wireY(940) + 6} L520 ${wireY(520) + 6}Z`); birds.forEach((b, i) => { if (b.state === 'perch' && roost) takeOff(b, true); if (b.state === 'gone') { if (!roost && Math.random() < dt * 0.5) { b.x = spots[i]; b.path = { p0: [rnd(0, 1) < 0.5 ? -30 : 990, rnd(30, 90)], c1: [rnd(300, 700), rnd(40, 100)], c2: [b.x + rnd(-60, 60), wireY(b.x) - 50], p1: [b.x, wireY(b.x) - 2.5], dur: rnd(2.2, 3.4) }; b.state = 'fly'; b.t = 0; } b.g.setAttribute('opacity', 0); return; } b.g.setAttribute('opacity', 1); let x, y, flying = false, ang = 0; if (b.state === 'fly') { b.t += dt; const u = clamp(b.t / b.path.dur, 0, 1); [x, y] = bez(b.path, ease(u)); const [x2] = bez(b.path, ease(Math.min(1, u + 0.02))); b.dir = x2 >= x ? 1 : -1; flying = u < 0.97; if (u >= 1) { if (b.path.away) { b.state = 'gone'; } else { b.state = 'perch'; b.x = x; b.next = rnd(0.6, 3); } } } else { // idle life on the wire: hop, turn, peck/preen, flick the tail b.next -= dt; if (b.next < 0) { b.next = rnd(0.8, 3.6); const r = Math.random(); if (r < 0.35) { b.hopT = 0; b.hopFrom = b.x; b.hopTo = clamp(b.x + b.dir * rnd(4, 9), 520, 935); } else if (r < 0.6) b.dir *= -1; else if (r < 0.8) b.peck = 1; else b.tail = 1; } if (b.hopT >= 0) { b.hopT += dt / 0.22; b.x = lerp(b.hopFrom, b.hopTo, ease(Math.min(1, b.hopT))); if (b.hopT >= 1) b.hopT = -1; } x = b.x; y = wireY(b.x) - 2.5 - (b.hopT >= 0 ? Math.sin(Math.PI * b.hopT) * 3.2 : 0); } b.peck = Math.max(0, b.peck - dt * 2); b.tail = Math.max(0, b.tail - dt * 3); const d = b.dir, pk = Math.sin(Math.PI * b.peck) * 1.6; const X = (dx) => f(x + dx * d); b.body.setAttribute('d', oval(x, y - 2.8, 3.1, 2.4)); b.cap.setAttribute('d', `M${X(0.8)} ${f(y - 5.6 + pk)} a2 1.8 0 0 1 ${f(3.6 * d)} 0Z`); b.cap.setAttribute('fill', rgb(mix(hex('#7a5a3c'), hex('#3a2c22'), P.inkT * 0.5))); b.cheek.setAttribute('d', oval(x + 2.6 * d, y - 4.4 + pk, 0.6, 0.6)); b.beak.setAttribute('d', `M${X(4.4)} ${f(y - 5.2 + pk)} L${X(6)} ${f(y - 4.8 + pk)} L${X(4.4)} ${f(y - 4.3 + pk)}Z`); const tf = Math.sin(b.tail * 20) * 1.6 * b.tail; b.tailN.setAttribute('d', `M${X(-2.4)} ${f(y - 2.6)} L${X(-6)} ${f(y - 0.6 - tf)}`); b.wing.setAttribute('d', flying ? '' : `M${X(-1.6)} ${f(y - 3.6)} Q${X(0.6)} ${f(y - 2.2)} ${X(-2.2)} ${f(y - 1.4)}`); b.legs.setAttribute('d', flying ? '' : `M${X(-0.4)} ${f(y - 0.6)} l0 1.2 M${X(0.8)} ${f(y - 0.6)} l0 1.2`); const fl = Math.sin(t * 34 + i) * 4; b.wings.setAttribute('d', flying ? `M${X(0)} ${f(y - 3.4)} L${X(-2)} ${f(y - 3.4 - fl)} M${X(0.6)} ${f(y - 3)} L${X(2.4)} ${f(y - 3 - fl * 0.8)}` : ''); }); }, }; } // ===================================================================== swallows (day) export function createSwallows(parent) { const birds = [0, 1].map((i) => ({ n: blot(parent), a: rnd(0, 6), b: rnd(0, 6), sp: rnd(0.8, 1.1) * (i ? -1 : 1), lx: 0, ly: 0 })); return { draw(t, dt, P) { birds.forEach((s) => { const tt = t * 0.32 * s.sp; const x = 480 + 440 * Math.sin(tt + s.a), y = 150 + 55 * Math.sin(tt * 2.3 + s.b) + 18 * Math.sin(tt * 5.1); const vx = x - (s.lx || x), vy = y - (s.ly || y); s.lx = x; s.ly = y; const ang = Math.atan2(vy, vx) * 57.3; const flap = Math.sin(t * 22 + s.a) > 0.4 ? 0.55 : 1; s.n.setAttribute('d', `M7 0 L2.4 -1 L${-3} ${-6.4 * flap} L-0.6 -1.2 L-7 -2.6 L-4.6 0 L-7 2.6 L-0.6 1.2 L${-3} ${6.4 * flap} L2.4 1Z`); s.n.setAttribute('transform', `translate(${f(x)} ${f(y)}) rotate(${f(ang)}) scale(0.8)`); s.n.setAttribute('opacity', f(1 - P.night)); }); }, }; } // ===================================================================== cherry petals export function createPetals(parent, { blossoms, canal }) { const petals = []; const add = (burst) => { const [x, y] = blossoms[(Math.random() * blossoms.length) | 0]; const toWater = Math.random() < 0.35; petals.push({ x, y, vx: rnd(-6, 6), vy: burst ? rnd(-10, 2) : rnd(2, 7), r: rnd(0, 6), ph: rnd(0, 6), life: 0, rest: 0, land: toWater ? WATER + rnd(4, 40) : rnd(BASE + 2, EDGE - 2), toWater, n: el('path', { fill: '#f6dfe4', stroke: 'currentColor', 'stroke-width': SP * 0.4 }, parent) }); }; return { burst(n = 40) { for (let i = 0; i < n; i++) add(true); }, draw(t, dt, P, wind) { if (Math.random() < dt * (1.4 + Math.abs(wind) * 1.4)) add(false); for (let i = petals.length - 1; i >= 0; i--) { const p = petals[i]; p.life += dt; if (p.y < p.land) { p.vy = lerp(p.vy, 11, dt * 1.4); p.x += (p.vx + wind * 22 + Math.sin(p.life * 2.6 + p.ph) * 9) * dt; p.y += p.vy * dt; p.r += dt * 3.4; } else if (p.toWater) { canal.floatPetal(p); p.n.remove(); petals.splice(i, 1); continue; } else p.rest += dt; const op = p.rest > 3 ? Math.max(0, 1 - (p.rest - 3)) : 1; const sx = Math.abs(Math.cos(p.r * 1.3)) * 0.8 + 0.25; p.n.setAttribute('d', `M${f(p.x - 1.8 * sx)} ${f(p.y)} Q${f(p.x)} ${f(p.y - 1.4)} ${f(p.x + 1.8 * sx)} ${f(p.y)} L${f(p.x + 1.2 * sx)} ${f(p.y + 0.4)} L${f(p.x + 1.8 * sx)} ${f(p.y + 0.9)} Q${f(p.x)} ${f(p.y + 1.6)} ${f(p.x - 1.8 * sx)} ${f(p.y)}Z`); p.n.setAttribute('transform', `rotate(${f(Math.sin(p.r) * 70)} ${f(p.x)} ${f(p.y)})`); p.n.setAttribute('opacity', f(op)); p.n.setAttribute('fill', rgb(mix(hex('#f6dfe4'), hex('#8a7480'), P.inkT * 0.6))); if (op <= 0 || p.x > W + 20 || p.x < -20) { p.n.remove(); petals.splice(i, 1); } } }, }; } // ===================================================================== smoke from the bath-house chimney export function createSmoke(parent, [cx, cy]) { const puffs = []; let acc = 0; return { draw(t, dt, P, wind, tau) { const firing = tau > 0.55 || tau < 0.08; // the bath fires up in the afternoon acc += dt; if (firing && acc > 0.55) { acc = 0; puffs.push({ x: cx + rnd(-2, 2), y: cy, r: rnd(3, 4.5), life: 0, ph: rnd(0, 6), n: shape(parent, SP * 0.7) }); } for (let i = puffs.length - 1; i >= 0; i--) { const p = puffs[i]; p.life += dt; p.x += (4 + wind * 10 + Math.sin(p.life * 1.2 + p.ph) * 2) * dt; p.y -= (9 - p.life * 0.6) * dt; p.r += dt * 2.2; const pts = []; for (let k = 0; k <= 14; k++) { const a = (k / 14) * Math.PI * 2; const rr = p.r * (1 + 0.16 * Math.sin(a * 3 + p.ph + p.life)); pts.push([p.x + Math.cos(a) * rr, p.y + Math.sin(a) * rr * 0.8]); } p.n.setAttribute('d', 'M' + pts.map(pt).join('L') + 'Z'); p.n.setAttribute('opacity', f(Math.max(0, 0.9 - p.life / 7))); if (p.life > 6.3) { p.n.remove(); puffs.splice(i, 1); } } }, }; }examples/village/houses.ts30 KB4fa5d54b86ebupstream ↗
// The street: four machiya-style buildings and an alley, drawn once, plus the // parts that live (windows that light, noren and lanterns in the wind, the // fūrin, a sliding shoji someone opens). import { el, pen, shape, blot, f, pt, limb, PAPER } from '../../lib/ink.ts'; import { BASE, SP, srnd, lerp, clamp, smooth, ease, oval, rgb, hex, mix, wobble } from './kit.ts'; const JP = '"Hiragino Mincho ProN","Yu Mincho","YuMincho","Noto Serif JP","Songti SC",serif'; const RED = hex('#b3412d'), RED_NIGHT = hex('#6e2a22'), WARM = hex('#ffcf7e'), WARM_DEEP = hex('#f3a54d'); // ------------------------------------------------------------------ drawing kit const P = (g, d, w = SP) => { const n = pen(g, w); n.setAttribute('d', d); return n; }; const S = (g, d, w = SP) => { const n = shape(g, w); n.setAttribute('d', d); return n; }; const B = (g, d) => { const n = blot(g); n.setAttribute('d', d); return n; }; const rect = (x0, y0, x1, y1) => `M${x0} ${y0} L${x1} ${y0} L${x1} ${y1} L${x0} ${y1}Z`; function text(g, x, y, s, size, { vertical = false, weight = 600, anchor = 'middle', fill = 'currentColor' } = {}) { const n = el('text', { x, y, 'font-size': size, 'font-family': JP, 'font-weight': weight, fill, 'text-anchor': anchor, 'dominant-baseline': 'central' }, g); if (vertical) { n.setAttribute('writing-mode', 'vertical-rl'); n.setAttribute('glyph-orientation-vertical', '0'); } n.textContent = s; return n; } /** Tiled roof seen from the street: sweeping eave (sori), round tile ends, rafters, stacked ridge with oni tiles. */ function roof(g, { x0, x1, eave, ridge, inset, tile = 5.6, sori = 2.8, depth = 2.6, oni = true, rafters = true }) { const cx = (x0 + x1) / 2; const eaveY = (x) => eave - sori * Math.pow(Math.abs(x - cx) / ((x1 - x0) / 2), 2.2); S(g, `M${x0} ${eaveY(x0)} Q${cx} ${eave + sori * 0.6} ${x1} ${eaveY(x1)} L${x1 - inset} ${ridge} L${x0 + inset} ${ridge}Z`); // tile channels: a line from each round tile end up to the ridge, slightly concave const ch = [], ends = []; for (let x = x0 + tile * 0.8; x < x1 - tile * 0.4; x += tile) { const t = (x - x0) / (x1 - x0), ey = eaveY(x) - 0.4; const top = lerp(x0 + inset, x1 - inset, t); ch.push(`M${f(x)} ${f(ey - 1.6)} Q${f(lerp(x, top, 0.5) + (t - 0.5) * 2)} ${f(lerp(ey, ridge, 0.55))} ${f(top)} ${ridge + 1}`); ends.push(oval(x, ey, 1.35, 1.35)); } P(g, ch.join(' '), SP * 0.5); const tiles = el('path', { d: ends.join(' '), fill: PAPER, stroke: 'currentColor', 'stroke-width': SP * 0.55 }, g); // fascia + rafter ends under the eave P(g, `M${x0 + 1} ${eaveY(x0) + depth} Q${cx} ${eave + sori * 0.6 + depth} ${x1 - 1} ${eaveY(x1) + depth}`, SP * 0.7); if (rafters) { const r = []; for (let x = x0 + 5; x < x1 - 3; x += 4.2) r.push(`M${f(x)} ${f(eaveY(x) + depth + 0.6)} l0 1.8`); P(g, r.join(' '), SP * 0.6); } // ridge: stacked noshi tiles const rx0 = x0 + inset - 4, rx1 = x1 - inset + 4; S(g, rect(rx0, ridge - 5.5, rx1, ridge + 0.5), SP * 0.9); P(g, `M${rx0} ${ridge - 2.6} L${rx1} ${ridge - 2.6}`, SP * 0.5); if (oni) [rx0, rx1].forEach((x, i) => { const s = i ? 1 : -1; S(g, `M${x} ${ridge + 0.5} L${x} ${ridge - 6} Q${x + s * 0.5} ${ridge - 11} ${x + s * 4.5} ${ridge - 12} Q${x + s * 6.5} ${ridge - 9} ${x + s * 5} ${ridge - 6} L${x + s * 5} ${ridge + 0.5}Z`, SP * 0.85); P(g, `M${x + s * 1.6} ${ridge - 4} q${s * 1.4} -1 ${s * 1.8} 1`, SP * 0.5); }); return { tiles }; } /** Sen-bon kōshi: fine vertical slats with a rhythm, rails top and bottom, short kiriko slats above the upper rail. */ function koshi(g, x0, x1, y0, y1, { gap = 2.3 } = {}) { const top = y0 + (y1 - y0) * 0.16; S(g, rect(x0, y0, x1, y1), SP * 0.9); const d = [`M${x0} ${f(top)} L${x1} ${f(top)}`, `M${x0} ${y1 - 3} L${x1} ${y1 - 3}`]; let k = 0; for (let x = x0 + gap; x < x1 - 0.5; x += gap, k++) { if (k % 4 === 3) d.push(`M${f(x)} ${y0} L${f(x)} ${y1}`); else d.push(`M${f(x)} ${f(top)} L${f(x)} ${y1 - 3}`); } P(g, d.join(' '), SP * 0.55); } /** Plaster window with fat vertical bars (mushiko-mado). */ function mushiko(g, x0, y0, x1, y1) { S(g, `M${x0 + 3} ${y0} L${x1 - 3} ${y0} Q${x1} ${y0} ${x1} ${y0 + 3} L${x1} ${y1 - 3} Q${x1} ${y1} ${x1 - 3} ${y1} L${x0 + 3} ${y1} Q${x0} ${y1} ${x0} ${y1 - 3} L${x0} ${y0 + 3} Q${x0} ${y0} ${x0 + 3} ${y0}Z`, SP); const d = []; for (let x = x0 + 4; x < x1 - 3; x += 5) d.push(`M${x} ${y0 + 2.5} Q${x - 0.6} ${(y0 + y1) / 2} ${x} ${y1 - 2.5} M${x + 2.4} ${y0 + 2.5} Q${x + 1.8} ${(y0 + y1) / 2} ${x + 2.4} ${y1 - 2.5}`); P(g, d.join(' '), SP * 0.55); } /** Inuyarai: curved bamboo fence along the base of the wall. */ function inuyarai(g, x0, x1, y0) { const d = [`M${x0} ${y0 + 1} Q${(x0 + x1) / 2} ${y0 - 1} ${x1} ${y0 + 1}`, `M${x0 - 1} ${BASE - 1} L${x1 + 1} ${BASE - 1}`]; for (let x = x0 + 1.5; x < x1; x += 2.6) d.push(`M${f(x)} ${y0 + 1} Q${f(x + 0.4)} ${f((y0 + BASE) / 2 + 3)} ${f(x - 0.6)} ${BASE - 1}`); P(g, d.join(' '), SP * 0.5); } /** A window pane that lights up at night (drawn first; lattice goes on top). */ function pane(g, glowG, x0, y0, x1, y1, { thr = srnd(0.15, 0.6), lateOff = srnd(0, 1) < 0.45 ? srnd(0.93, 1.12) : 9, warmth = srnd(0, 1) } = {}) { const n = el('path', { d: rect(x0, y0, x1, y1), fill: PAPER }, g); const glow = el('ellipse', { cx: (x0 + x1) / 2, cy: (y0 + y1) / 2, rx: (x1 - x0) * 0.9 + 10, ry: (y1 - y0) * 0.9 + 10, fill: 'url(#v-warmglow)', opacity: 0 }, glowG); return { n, glow, thr, lateOff, warmth, x0, y0, x1, y1, lit: 0 }; } /** Wind-blown noren hanging from a rod. */ function noren(g, x0, x1, y, len, panels, label, { open = [0.28, 0.88], red = false } = {}) { const grp = el('g', {}, g); P(grp, `M${x0 - 2} ${y} L${x1 + 2} ${y}`, SP * 1.2); const w = (x1 - x0) / panels; const cloth = Array.from({ length: panels }, (_, i) => ({ x: x0 + i * w, w: w - 0.8, n: el('path', { fill: red ? rgb(RED) : PAPER, stroke: 'currentColor', 'stroke-width': SP * 0.8, 'stroke-linejoin': 'round' }, grp), a: 0, v: 0, ph: srnd(0, 6) })); const label_ = text(grp, (x0 + x1) / 2, y + len * 0.48, label, Math.min(len * 0.42, w * 0.95), { weight: 700, fill: red ? '#fbf3e6' : 'currentColor' }); return { grp, cloth, label: label_, y, len, open, red, x0, x1, show: 1, draw(t, dt, wind, tau, P_) { const [o0, o1] = this.open; const isOpen = o1 > 1 ? tau > o0 || tau < o1 - 1 : tau > o0 && tau < o1; this.show = this.first === undefined ? (this.first = 1, isOpen ? 1 : 0) : clamp(this.show + (isOpen ? dt : -dt) * 0.8, 0, 1); this.grp.setAttribute('opacity', f(this.show)); this.grp.setAttribute('transform', `translate(0 ${f(-(1 - ease(this.show)) * 6)})`); if (this.red) this.cloth.forEach((c) => c.n.setAttribute('fill', rgb(mix(RED, RED_NIGHT, P_.inkT)))); let sw = 0; this.cloth.forEach((c, i) => { c.v += (-c.a * 22 + wind * 2.2 + Math.sin(t * 1.7 + c.ph) * 0.6 - c.v * 3.2) * dt; c.a += c.v * dt; const s = c.a * this.len * 0.45, flt = Math.sin(t * 3.1 + i) * 0.5; c.n.setAttribute('d', `M${f(c.x)} ${this.y} L${f(c.x + c.w)} ${this.y} Q${f(c.x + c.w + s * 0.4)} ${f(this.y + this.len * 0.6)} ${f(c.x + c.w + s + flt)} ${f(this.y + this.len)} L${f(c.x + s + flt)} ${f(this.y + this.len - 0.6)} Q${f(c.x + s * 0.4)} ${f(this.y + this.len * 0.6)} ${f(c.x)} ${this.y}Z`); sw += s; }); this.label.setAttribute('transform', `translate(${f(sw / this.cloth.length * 0.6)} 0)`); }, poke() { this.cloth.forEach((c) => (c.v += 3 + Math.random() * 2)); }, }; } /** Chōchin lantern hanging from a hook, swinging, glowing at night. */ function chochin(g, glowG, x, y, { r = 7, h = 16, label = '', red = false } = {}) { const grp = el('g', {}, g); const body = el('path', { d: `M${-r * 0.75} 4 Q${-r * 1.18} ${4 + h / 2} ${-r * 0.75} ${4 + h} L${r * 0.75} ${4 + h} Q${r * 1.18} ${4 + h / 2} ${r * 0.75} 4Z`, fill: red ? rgb(RED) : PAPER, stroke: 'currentColor', 'stroke-width': SP * 0.8 }, grp); const ribs = []; for (let k = 1; k < 5; k++) { const yy = 4 + (h * k) / 5, wv = r * (1.18 - 0.3 * Math.abs(k / 5 - 0.5) * 2); ribs.push(`M${f(-wv * 0.95)} ${f(yy)} Q0 ${f(yy + 1)} ${f(wv * 0.95)} ${f(yy)}`); } P(grp, ribs.join(' '), SP * 0.4); B(grp, `M${-r * 0.6} 2 L${r * 0.6} 2 L${r * 0.6} 4.4 L${-r * 0.6} 4.4Z M${-r * 0.6} ${4 + h - 0.4} L${r * 0.6} ${4 + h - 0.4} L${r * 0.6} ${6.4 + h} L${-r * 0.6} ${6.4 + h}Z`); P(grp, 'M0 -4 L0 2', SP * 0.5); const lbl = label ? text(grp, 0, 4 + h / 2, label, h * 0.42, { vertical: label.length > 1, weight: 700, fill: red ? '#fbf3e6' : 'currentColor' }) : null; const glow = el('circle', { r: 30 + r, fill: 'url(#v-warmglow)', opacity: 0 }, glowG); return { grp, body, glow, lbl, x, y, h, red, a: srnd(-0.05, 0.05), v: 0, ph: srnd(0, 6), thr: srnd(0.1, 0.3), draw(t, dt, wind, P_) { this.v += (-this.a * 10 + wind * 0.5 + Math.sin(t * 0.9 + this.ph) * 0.15 - this.v * 1.1) * dt; this.a += this.v * dt; this.grp.setAttribute('transform', `translate(${this.x} ${this.y}) rotate(${f(-this.a * 57.3)})`); const lit = smooth(this.thr, this.thr + 0.2, P_.lamp); const base = this.red ? mix(RED, RED_NIGHT, P_.inkT * (1 - lit)) : P_.paper; this.body.setAttribute('fill', rgb(mix(base, this.red ? hex('#ff8a4a') : WARM, lit * 0.95))); const cx = this.x + Math.sin(this.a) * -(this.h / 2 + 4), cy = this.y + Math.cos(this.a) * (this.h / 2 + 4); this.glow.setAttribute('cx', f(cx)); this.glow.setAttribute('cy', f(cy)); this.glow.setAttribute('opacity', f(lit * (0.85 + 0.15 * Math.sin(t * 7 + this.ph) * Math.sin(t * 3.3)))); }, poke() { this.v += (Math.random() < 0.5 ? -1 : 1) * (1.8 + Math.random()); }, }; } // ------------------------------------------------------------------ the street export function buildStreet(layers, defs) { const { back, houses: hg, front, glow } = layers; const g = (parent) => el('g', {}, parent); const glowGrad = el('radialGradient', { id: 'v-warmglow' }, defs); el('stop', { offset: 0, 'stop-color': '#ffd58a', 'stop-opacity': 0.75 }, glowGrad); el('stop', { offset: 0.45, 'stop-color': '#ffb85c', 'stop-opacity': 0.28 }, glowGrad); el('stop', { offset: 1, 'stop-color': '#ffb85c', 'stop-opacity': 0 }, glowGrad); const windows = [], lanterns = [], norens = []; // ---------- cherry tree behind the roofs (canopy rises above the alley) const tree = g(back); P(tree, 'M452 344 Q450 300 446 268 Q440 236 420 214 M462 344 Q463 300 468 262 Q474 236 500 214 M447 262 Q458 248 456 226 Q455 206 462 192', SP * 1.1); P(tree, 'M430 224 l-10 -6 M490 222 l12 -4 M456 212 l-8 -10 M468 236 q10 -4 14 -12', SP * 0.7); const canopy = g(tree); const blossoms = []; [[414, 206, 26], [502, 200, 28], [458, 176, 30], [434, 186, 22], [486, 180, 22], [460, 204, 26], [520, 216, 18], [400, 222, 18]].forEach(([cx, cy, r]) => { const pts = []; for (let i = 0; i <= 60; i++) { const a = (i / 60) * Math.PI * 2; const rr = r + 2 * Math.abs(Math.sin(a * 6.5)) - 0.6 * Math.sin(a * 3); pts.push([cx + rr * Math.cos(a), cy + rr * 0.78 * Math.sin(a)]); } S(canopy, 'M' + pts.map(pt).join('L') + 'Z', SP * 0.8); }); const fl = []; for (let i = 0; i < 110; i++) { const a = srnd(0, 6.28), d = Math.sqrt(srnd(0, 1)); const [cx, cy, r] = [[458, 196, 54], [414, 210, 26], [502, 204, 28]][i % 3]; const x = cx + Math.cos(a) * r * d * 0.95, y = cy + Math.sin(a) * r * 0.62 * d; blossoms.push([x, y]); const s = srnd(0.8, 1.3); fl.push(`M${f(x)} ${f(y - s)} l${f(s * 0.95)} ${f(s * 0.7)} l${f(-s * 0.4)} ${f(s * 1.1)} l${f(-s * 1.1)} 0 l${f(-s * 0.4)} ${f(-s * 1.1)}Z`); } P(canopy, fl.join(' '), SP * 0.45); // ---------- alley between H2 and H3: stone path to a small gate and a lantern const alley = g(back); S(alley, rect(432, 250, 482, BASE), SP * 0.6); // side walls receding to a small gate; plank lines follow the perspective S(alley, 'M432 258 L449 286 L449 306 L432 344Z', SP * 0.6); S(alley, 'M482 258 L465 286 L465 306 L482 344Z', SP * 0.6); P(alley, 'M436 265 L436 337 M440 271 L440 330 M444 278 L444 322 M478 265 L478 337 M474 271 L474 330 M470 278 L470 322', SP * 0.4); S(alley, rect(449, 288, 465, 306), SP * 0.7); S(alley, 'M446 289 L468 289 L465 283 L449 283Z', SP * 0.7); P(alley, 'M457 289 L457 306', SP * 0.5); // stepping stones shrinking into the distance [[457, 339, 7, 2.4], [456, 328, 5.6, 1.9], [458, 319, 4.4, 1.5], [457, 312, 3.4, 1.1]].forEach(([x, y, rx, ry]) => S(alley, oval(x, y, rx, ry), SP * 0.5)); const alleyLamp = pane(alley, glow, 453.5, 293, 460.5, 301, { thr: 0.05, lateOff: 9 }); P(alley, 'M457 293 L457 301 M453.5 297 L460.5 297', SP * 0.4); // ================= H1 · sake shop (酒屋) x 18–236 const h1 = g(hg); [[26, 206], [220, 206]].forEach(([x, y]) => { S(h1, rect(x, y + 4, x + 8, 262), SP * 0.8); S(h1, `M${x - 3} ${y + 5} L${x + 11} ${y + 5} L${x + 8} ${y} L${x} ${y}Z`, SP * 0.7); }); S(h1, rect(32, 214, 222, 262)); roof(h1, { x0: 12, x1: 242, eave: 218, ridge: 184, inset: 28 }); mushiko(h1, 46, 230, 128, 252); // horizontal signboard under the eave S(h1, rect(140, 228, 212, 250), SP * 1.1); P(h1, rect(142.5, 230.5, 209.5, 247.5), SP * 0.5); text(h1, 176, 239.5, '白梅 酒', 11.5, { weight: 800 }); S(h1, rect(20, 270, 234, BASE)); roof(h1, { x0: 14, x1: 240, eave: 274, ridge: 262, inset: 6, tile: 5, sori: 1.4, oni: false }); windows.push(pane(h1, glow, 28, 284, 88, 336)); koshi(h1, 26, 90, 280, 340); // door with noren S(h1, rect(114, 280, 166, BASE), SP * 0.9); windows.push(pane(h1, glow, 117, 283, 163, BASE - 1, { thr: 0.05, lateOff: 0.9 })); P(h1, 'M117 314 L163 314 M140 283 L140 344', SP * 0.45); norens.push(noren(h1, 116, 164, 281, 26, 3, '酒', { open: [0.29, 0.86] })); // sake barrels (komodaru) stacked to the right const barrel = (x, y, w, h) => { S(h1, `M${x} ${y + 2} Q${x + w / 2} ${y - 1} ${x + w} ${y + 2} L${x + w} ${y + h - 2} Q${x + w / 2} ${y + h + 1} ${x} ${y + h - 2}Z`, SP * 0.9); P(h1, `M${x} ${y + 6} Q${x + w / 2} ${y + 3.5} ${x + w} ${y + 6} M${x} ${y + h - 6} Q${x + w / 2} ${y + h - 3.5} ${x + w} ${y + h - 6} M${x + 3} ${y + 1} L${x + 3} ${y + h - 1} M${x + w - 3} ${y + 1} L${x + w - 3} ${y + h - 1}`, SP * 0.5); S(h1, oval(x + w / 2, y + h / 2, w * 0.24, h * 0.24), SP * 0.6); text(h1, x + w / 2, y + h / 2, '酒', w * 0.26, { weight: 800 }); }; barrel(172, 318, 28, 26); barrel(202, 318, 28, 26); barrel(187, 292, 28, 26); // sugidama (cedar ball) hanging by the door P(h1, 'M102 274 L102 280', SP * 0.6); const sug = []; for (let i = 0; i < 360; i++) { const a = srnd(0, 6.28), d = Math.sqrt(srnd(0, 1)) * 11.2; const x = 102 + Math.cos(a) * d, y = 292 + Math.sin(a) * d; const b = srnd(0, 6.28); sug.push(`M${f(x)} ${f(y)} l${f(Math.cos(b) * 1.6)} ${f(Math.sin(b) * 1.6)}`); } S(h1, oval(102, 292, 12, 12), SP * 0.8); P(h1, sug.join(' '), SP * 0.45); P(h1, 'M97 303 l10 0 M100 303 l-1 5 M105 303 l1 5', SP * 0.5); // ================= H2 · house with balcony x 236–432 const h2 = g(hg); S(h2, rect(246, 200, 424, 260)); roof(h2, { x0: 230, x1: 438, eave: 204, ridge: 168, inset: 26 }); // upper shoji windows (left one slides open on click) const shojiWin = pane(h2, glow, 262, 212, 318, 250, { thr: 0.12, lateOff: 1.08 }); windows.push(shojiWin); const interior = g(h2); // revealed when the shoji slides const room = el('path', { d: rect(262, 212, 318, 250), fill: '#3a2c22' }, interior); const person = g(interior); S(person, 'M294 250 Q295 236 304 234 Q313 236 314 250Z', SP * 0.8); const face = S(person, oval(304, 227, 5, 6), SP * 0.8); B(person, 'M298.6 226 Q299 219 304 219 Q309.4 219 309.4 226 Q307 222.5 304 223 Q301 222.5 298.6 226Z M302 219.4 a2.6 2.2 0 1 1 4 0Z'); const waveArm = limb(person, 3, SP * 0.7); const slide = g(h2); // the sliding panel const shojiGrid = (gg, x0, y0, x1, y1, cols, rows) => { const d = [rect(x0, y0, x1, y1)]; for (let i = 1; i < cols; i++) { const x = lerp(x0, x1, i / cols); d.push(`M${f(x)} ${y0} L${f(x)} ${y1}`); } for (let j = 1; j < rows; j++) { const y = lerp(y0, y1, j / rows); d.push(`M${x0} ${f(y)} L${x1} ${f(y)}`); } P(gg, d.join(' '), SP * 0.5); }; const slidePane = el('path', { d: rect(290, 212, 318, 250), fill: PAPER }, slide); shojiGrid(slide, 290, 212, 318, 250, 3, 5); shojiGrid(h2, 262, 212, 290, 250, 3, 5); P(h2, rect(262, 212, 318, 250), SP); windows.push(pane(h2, glow, 340, 212, 404, 250, { thr: 0.3 })); shojiGrid(h2, 340, 212, 372, 250, 3, 5); shojiGrid(h2, 372, 212, 404, 250, 3, 5); P(h2, rect(340, 212, 404, 250), SP); // balcony rail const rail = g(h2); S(rail, rect(250, 238, 418, 258), SP * 0.8); const bal = []; for (let x = 254; x < 416; x += 5.2) bal.push(`M${f(x)} 241 L${f(x)} 256`); P(rail, bal.join(' ') + ' M250 241 L418 241', SP * 0.5); S(h2, rect(240, 268, 428, BASE)); roof(h2, { x0: 232, x1: 436, eave: 272, ridge: 260, inset: 6, tile: 5, sori: 1.4, oni: false }); windows.push(pane(h2, glow, 246, 282, 294, 322)); koshi(h2, 244, 296, 278, 324); windows.push(pane(h2, glow, 366, 282, 422, 322, { thr: 0.25 })); koshi(h2, 364, 424, 278, 324); inuyarai(h2, 244, 296, 326); inuyarai(h2, 364, 424, 326); // lattice sliding entrance door S(h2, rect(304, 278, 356, BASE), SP * 0.9); windows.push(pane(h2, glow, 306, 280, 354, BASE - 1, { thr: 0.2 })); const dd = []; for (let x = 308; x < 354; x += 3.4) dd.push(`M${f(x)} 280 L${f(x)} 343`); for (let y = 290; y < 342; y += 12) dd.push(`M306 ${y} L354 ${y}`); P(h2, dd.join(' ') + ' M330 280 L330 344', SP * 0.45); S(h2, rect(316, 270, 344, 276), SP * 0.6); text(h2, 330, 273, '伊 藤', 4.6, { weight: 700 }); // potted plants at the door ([[298, 'pine'], [360, 'asagao']] as Array<[number, string]>).forEach(([x, kind]) => { S(h2, `M${x - 5} 336 L${x + 5} 336 L${x + 4} ${BASE} L${x - 4} ${BASE}Z`, SP * 0.7); if (kind === 'pine') { P(h2, `M${x} 336 Q${x - 3} 330 ${x + 1} 325 Q${x + 4} 321 ${x - 1} 316 M${x + 1} 325 Q${x + 5} 324 ${x + 7} 321`, SP * 0.8); [[x - 4, 324, 5.2], [x + 6, 319.5, 4], [x - 1, 314, 4.4]].forEach(([px, py, r]) => { S(h2, `M${px - r} ${py} Q${px - r * 0.8} ${py - 2.6} ${px - r * 0.3} ${py - 2.2} Q${px} ${py - 3.4} ${px + r * 0.4} ${py - 2.4} Q${px + r} ${py - 2.2} ${px + r} ${py} Q${px} ${py + 1} ${px - r} ${py}Z`, SP * 0.6); P(h2, Array.from({ length: 4 }, (_, k) => `M${f(px - r * 0.6 + k * r * 0.4)} ${py - 0.5} l0.6 -1.4`).join(' '), SP * 0.35); }); } else { P(h2, `M${x - 2} 336 L${x - 2} 300 M${x + 2} 336 L${x + 2} 300 M${x - 3} 312 L${x + 3} 312 M${x - 3} 324 L${x + 3} 324`, SP * 0.5); P(h2, `M${x} 334 q-4 -8 1 -14 q4 -6 -1 -12 q-3 -4 1 -8`, SP * 0.5); [[x - 3, 316], [x + 3, 306], [x - 2, 326]].forEach(([fx, fy]) => S(h2, oval(fx, fy, 2.2, 1.8), SP * 0.5)); } }); // fūrin under the main eave const furinG = g(h2); // ================= H3 · tea house (茶屋) x 482–704 const h3 = g(hg); S(h3, rect(496, 224, 690, 256)); roof(h3, { x0: 476, x1: 710, eave: 228, ridge: 196, inset: 24 }); mushiko(h3, 520, 232, 668, 250); S(h3, rect(486, 264, 700, BASE)); roof(h3, { x0: 478, x1: 708, eave: 268, ridge: 256, inset: 5, tile: 5, sori: 1.6, oni: false }); // open shop front: interior (lights up), counter, menu tags, sudare windows.push(pane(h3, glow, 492, 272, 614, 330, { thr: 0.02, lateOff: 0.94 })); P(h3, 'M496 308 L610 308', SP * 0.55); const tags = ['だんご', '甘酒', '抹茶', 'おしるこ', '草餅']; tags.forEach((s, i) => { const x = 506 + i * 22; P(h3, `M${x} 283 L${x} 285.5`, SP * 0.4); S(h3, rect(x - 5, 285.5, x + 5, 307), SP * 0.6); text(h3, x, 296.2, s, 4.6, { vertical: true, weight: 700 }); }); S(h3, rect(490, 318, 616, 324), SP * 0.9); // counter P(h3, 'M494 324 L494 344 M612 324 L612 344', SP * 0.7); // dango on a plate on the counter [528, 574].forEach((x) => { S(h3, `M${x - 9} 318 Q${x} 321 ${x + 9} 318 Z`, SP * 0.6); P(h3, `M${x - 7} 315 L${x + 8} 307`, SP * 0.6); [0, 1, 2].forEach((k) => S(h3, oval(x - 4 + k * 4.4, 313.5 - k * 2.4, 2.3, 2.3), SP * 0.6)); }); const sudare = g(h3); S(sudare, rect(490, 270, 616, 282), SP * 0.7); P(sudare, Array.from({ length: 5 }, (_, i) => `M490 ${272 + i * 2} L616 ${272 + i * 2}`).join(' ') + ' M520 268 L520 284 M586 268 L586 284', SP * 0.35); S(sudare, `M488 268.5 a2.5 2.5 0 0 0 0 5 L618 273.5 a2.5 2.5 0 0 0 0 -5Z`, SP * 0.7); // entrance with noren S(h3, rect(620, 270, 694, BASE), SP * 0.9); windows.push(pane(h3, glow, 622, 272, 692, BASE - 1, { thr: 0.02, lateOff: 0.95 })); norens.push(noren(h3, 624, 690, 271, 24, 4, '茶', { open: [0.31, 0.9] })); lanterns.push(chochin(h3, glow, 498, 268, { r: 6.4, h: 15, label: '茶', red: true })); lanterns.push(chochin(h3, glow, 696, 268, { r: 6.4, h: 15, label: '茶', red: true })); // bench (shōgi) and the red parasol (nodategasa) out front const out = g(front); S(out, `M586 351 L586 296 M589 351 L589 296`, SP * 0.6); P(out, 'M587.5 352 L587.5 262', SP * 0.9); let rimD = 'M536 273 Q548 256 587.5 252 Q627 256 639 273'; for (let i = 12; i > 0; i--) { const xa = lerp(536, 639, i / 12), xb = lerp(536, 639, (i - 1) / 12); rimD += ` Q${f((xa + xb) / 2)} 276.4 ${f(xb)} 273`; } const parasol = el('path', { d: rimD + 'Z', fill: rgb(RED), stroke: 'currentColor', 'stroke-width': SP * 0.8 }, out); P(out, Array.from({ length: 13 }, (_, i) => `M587.5 252.6 L${f(lerp(538, 637, i / 12))} 272.4`).join(' '), SP * 0.35); S(out, oval(587.5, 252, 3.2, 1.6), SP * 0.6); const benchTop = el('path', { d: rect(516, 330, 600, 336), fill: rgb(RED), stroke: 'currentColor', 'stroke-width': SP * 0.8 }, out); S(out, rect(514, 336, 602, 339), SP * 0.7); P(out, 'M520 339 L520 352 M596 339 L596 352 M522 339 L522 352 M594 339 L594 352 M520 348 L596 348', SP * 0.7); // a teacup and a plate left on the bench S(out, 'M584 330 L585 325 L591 325 L592 330Z', SP * 0.6); // ================= H4 · public bath (銭湯) x 704–948 const h4 = g(hg); // chimney behind the roof const chim = g(back); S(chim, 'M893 252 L895 72 L907 72 L909 252Z', SP); P(chim, 'M894.3 100 L907.7 100 M894 130 L908 130 M893.7 170 L908.3 170 M893.4 210 L908.6 210', SP * 0.55); S(chim, rect(892, 66, 910, 72), SP * 0.9); text(chim, 901, 150, 'ゆ', 9, { weight: 800 }); S(h4, rect(708, 252, 944, BASE)); roof(h4, { x0: 700, x1: 952, eave: 256, ridge: 214, inset: 44 }); // karahafu: undulating gable over the entrance S(h4, 'M766 262 Q780 262 790 250 Q806 226 826 222 Q846 226 862 250 Q872 262 886 262 L882 268 Q870 268 860 258 Q846 236 826 232 Q806 236 792 258 Q782 268 770 268Z', SP); P(h4, 'M790 252 Q806 230 826 226 Q846 230 862 252', SP * 0.5); S(h4, 'M821 222 Q826 214 831 222Z', SP * 0.7); P(h4, 'M800 262 L800 344 M852 262 L852 344', SP); windows.push(pane(h4, glow, 803, 266, 849, BASE - 1, { thr: 0.0, lateOff: 9 })); norens.push(noren(h4, 804, 848, 266, 30, 2, 'ゆ', { open: [0.6, 1.08], red: false })); // clerestory windows windows.push(pane(h4, glow, 716, 266, 774, 292, { thr: 0.05, lateOff: 9 })); windows.push(pane(h4, glow, 878, 266, 936, 292, { thr: 0.05, lateOff: 9 })); [[716, 774], [878, 936]].forEach(([a, b]) => shojiGrid(h4, a, 266, b, 292, 6, 2)); // signboard + wainscot S(h4, rect(714, 300, 734, 344), SP * 0.9); text(h4, 724, 322, '松の湯', 9, { vertical: true, weight: 800 }); const ws = []; for (let x = 740; x < 800; x += 4) ws.push(`M${x} 304 L${x} 344`); for (let x = 856; x < 940; x += 4) ws.push(`M${x} 304 L${x} 344`); P(h4, ws.join(' ') + ' M738 304 L800 304 M852 304 L940 304', SP * 0.5); // bucket pyramid (yellow bath pails) const pail = (x, y) => { const n = el('path', { d: `M${x - 6} ${y} L${x + 6} ${y} L${x + 5} ${y + 9} L${x - 5} ${y + 9}Z`, fill: '#e9c45a', stroke: 'currentColor', 'stroke-width': SP * 0.7 }, h4); P(h4, `M${x - 5.6} ${y + 2.4} L${x + 5.6} ${y + 2.4}`, SP * 0.4); return n; }; const pails = [pail(902, 335), pail(915, 335), pail(928, 335), pail(908.5, 326), pail(921.5, 326), pail(915, 317)]; // lanterns at the bath lanterns.push(chochin(h4, glow, 790, 262, { r: 5.6, h: 13, label: 'ゆ' })); lanterns.push(chochin(h4, glow, 862, 262, { r: 5.6, h: 13, label: 'ゆ' })); // ---------- utility pole, wires, street lamp (in front of the alley) const pole = g(front); S(pole, 'M465 352 L466.5 98 L470.5 98 L472 352Z', SP * 0.9); P(pole, 'M466 140 L471 140 M466 200 L471 200 M466 260 L471 260 M466 320 L471 320', SP * 0.5); S(pole, rect(446, 110, 490, 114), SP * 0.8); [450, 458, 478, 486].forEach((x) => S(pole, `M${x - 1.6} 110 L${x + 1.6} 110 L${x + 1.2} 105 L${x - 1.2} 105Z`, SP * 0.5)); S(pole, 'M472 140 Q480 140 480 146 L480 170 Q480 176 472 176Z', SP * 0.8); // transformer P(pole, 'M472 150 L479 150 M472 160 L479 160', SP * 0.45); // lamp arm P(pole, 'M466 226 Q452 222 446 230', SP * 0.8); S(pole, 'M439 230 L453 230 L450 236 L442 236Z', SP * 0.8); const streetLamp = el('ellipse', { cx: 446, cy: 237, rx: 3, ry: 1.6, fill: PAPER, stroke: 'currentColor', 'stroke-width': SP * 0.5 }, pole); const lampCone = el('path', { d: 'M441 237 L451 237 L496 352 L396 352Z', fill: 'url(#v-cone)', opacity: 0 }, glow); const cone = el('linearGradient', { id: 'v-cone', x1: 0, y1: 0, x2: 0, y2: 1 }, defs); el('stop', { offset: 0, 'stop-color': '#ffe2a8', 'stop-opacity': 0.5 }, cone); el('stop', { offset: 1, 'stop-color': '#ffe2a8', 'stop-opacity': 0.06 }, cone); const lampGlow = el('circle', { cx: 446, cy: 237, r: 34, fill: 'url(#v-warmglow)', opacity: 0 }, glow); // wires sag to both sides; sparrows sit on the right-hand wire const wireY = (x) => { if (x >= 488) { const u = (x - 488) / (970 - 488); return 112 + (108 - 112) * u + 26 * 4 * u * (1 - u); } const u = (446 - x) / (446 + 10); return 112 + (104 - 112) * u + 22 * 4 * u * (1 - u); }; const wires = g(back); const wd = []; for (const [a, b, off] of [[488, 970, 0], [446, -10, 0], [488, 970, 7], [446, -10, 7]]) { const pts = []; for (let k = 0; k <= 30; k++) { const x = lerp(a, b, k / 30); pts.push([x, wireY(x) + off * (1 + 0.3 * Math.sin(k))]); } wd.push('M' + pts.map(pt).join('L')); } P(wires, wd.join(' '), SP * 0.5); // ---------- the street itself const street = g(front); P(street, `M0 ${BASE} L960 ${BASE}`, SP); const cracks = []; for (let i = 0; i < 34; i++) { const x = srnd(0, 960), y = srnd(350, 380); cracks.push(`M${f(x)} ${f(y)} l${f(srnd(6, 16))} ${f(srnd(-0.4, 0.4))}`); } P(street, cracks.join(' '), SP * 0.45); // stone gutter slabs along the houses const gut = []; for (let x = 0; x < 960; x += srnd(16, 26)) gut.push(`M${f(x)} ${BASE} L${f(x)} ${BASE + 4}`); P(street, `M0 ${BASE + 4} L960 ${BASE + 4} ` + gut.join(' '), SP * 0.5); // ---------- fūrin (wind chime) under H2's eave const furin = (() => { const x = 412, y = 207; const grp = g(furinG); const cord = pen(grp, SP * 0.45), bell = el('path', { fill: '#e8f2f4', stroke: 'currentColor', 'stroke-width': SP * 0.7 }, grp); const clap = pen(grp, SP * 0.45), strip = el('path', { fill: PAPER, stroke: 'currentColor', 'stroke-width': SP * 0.55 }, grp); const rings = pen(grp, SP * 0.5); let a = 0, v = 0, sa = 0, sv = 0, ring = 0; return { x, y, draw(t, dt, wind) { v += (-a * 14 + wind * 0.9 + wobble(t * 0.7) * 0.4 - v * 1.4) * dt; a += v * dt; sv += (-(sa - a * 1.6) * 9 + wind * 2.2 + Math.sin(t * 2.3) * 0.6 - sv * 1.6) * dt; sa += sv * dt; ring = Math.max(0, ring - dt * 0.9); const bx = x + Math.sin(a) * 6, by = y + Math.cos(a) * 6; cord.setAttribute('d', `M${x} ${y - 3} L${f(bx)} ${f(by)}`); bell.setAttribute('d', `M${f(bx - 4)} ${f(by + 5)} Q${f(bx - 4.2)} ${f(by - 0.6)} ${f(bx)} ${f(by - 0.6)} Q${f(bx + 4.2)} ${f(by - 0.6)} ${f(bx + 4)} ${f(by + 5)}Z`); const cx = bx + Math.sin(sa) * 4, cy = by + 5 + Math.cos(sa) * 4; clap.setAttribute('d', `M${f(bx)} ${f(by)} L${f(cx)} ${f(cy)} M${f(cx - 0.8)} ${f(cy)} l1.6 0`); const sx = cx + Math.sin(sa) * 9, sy = cy + Math.cos(sa) * 9; strip.setAttribute('d', `M${f(cx - 1.6)} ${f(cy + 1)} L${f(cx + 1.6)} ${f(cy + 1)} L${f(sx + 1.6)} ${f(sy)} L${f(sx - 1.6)} ${f(sy)}Z`); rings.setAttribute('d', ring > 0.02 ? [7, 11].map((r) => `M${f(bx - r * 0.7)} ${f(by - r * 0.1 - 4)} Q${f(bx)} ${f(by - r - 4)} ${f(bx + r * 0.7)} ${f(by - r * 0.1 - 4)}`).join(' ') : ''); rings.setAttribute('opacity', f(ring)); }, poke() { v += 2.4; sv += 6; ring = 1; }, ring() { ring = 1; }, get swing() { return sv; }, }; })(); // ---------- the shoji someone opens const shoji = (() => { let s = -1; return { hit: rect(260, 210, 320, 252), poke() { if (s < 0) s = 0; }, draw(t, dt, P_) { let open = 0; if (s >= 0) { s += dt; open = s < 0.6 ? ease(s / 0.6) : s < 4.4 ? 1 : 1 - ease((s - 4.4) / 0.6); if (s > 5) s = -1; } slide.setAttribute('transform', `translate(${f(-open * 27.5)} 0)`); interior.setAttribute('opacity', f(open > 0.001 ? 1 : 0)); const lit = shojiWin.lit; room.setAttribute('fill', rgb(mix(hex('#4a3a2c'), hex('#f0a85a'), lit * 0.85))); // the person leans into view and waves const lean = ease(clamp((s - 0.4) / 0.6, 0, 1)) * (1 - ease(clamp((s - 4.0) / 0.5, 0, 1))); person.setAttribute('transform', `translate(${f((1 - lean) * 22)} 0)`); const wv = Math.sin(Math.max(0, s - 1) * 9) * 0.5 * lean; const sh = [297, 238], el2 = [293, 231], hand = [293 + Math.sin(wv) * 5, 222 - Math.cos(wv) * 2]; waveArm.draw([sh, el2, hand], [0.2, 0.2]); slidePane.setAttribute('fill', rgb(mix(P_.paper, WARM, lit * 0.9))); }, }; })(); return { windows, lanterns, norens, furin, shoji, blossoms, canopy, pails, parasol, benchTop, alleyLamp, bench: { x0: 518, x1: 598, y: 330 }, chimney: [901, 64] as [number, number], wireY, lamp: { node: streetLamp, cone: lampCone, glow: lampGlow, x: 446, y: 237 }, applyRed(P_) { const c = rgb(mix(RED, RED_NIGHT, P_.inkT)); parasol.setAttribute('fill', c); benchTop.setAttribute('fill', c); pails.forEach((p) => p.setAttribute('fill', rgb(mix(hex('#e9c45a'), hex('#6d6240'), P_.inkT)))); }, }; }examples/village/index.html1.8 KBf7af018516c5upstream ↗
<!doctype html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Ink Village</title> <meta name="description" content="A Japanese street in hand-inked line, alive from dawn to night."> <style> html,body{margin:0;height:100%;overflow:hidden;background:#ebe8e2} body{display:grid;place-items:center} /* the scene is a self-contained card; the page around it never changes */ .card{position:relative;width:min(94vw,calc((100vh - 48px) * 2));aspect-ratio:2/1;border-radius:18px;overflow:hidden; box-shadow:0 1px 0 rgba(255,255,255,.7) inset,0 0 0 1px rgba(40,34,26,.10),0 18px 50px -18px rgba(40,34,26,.35),0 4px 14px -6px rgba(40,34,26,.18); --ink:#1c1c1c;touch-action:none;isolation:isolate} #village,#village svg{display:block;width:100%;height:100%;user-select:none;-webkit-user-select:none} #village svg .pp{fill:var(--paper,#fdfdfc)} #village svg.scrubbing,#village svg.scrubbing *{cursor:grabbing!important} .hud{position:absolute;left:2.2%;top:3.4%;font:500 clamp(10px,1.25vw,15px)/1.3 "Iowan Old Style","Hiragino Mincho ProN","Yu Mincho",Georgia,serif;color:var(--ink);letter-spacing:.04em;pointer-events:none;opacity:.85} .hud b{font-weight:600;font-variant-numeric:tabular-nums;letter-spacing:.06em} .hud span{margin-left:6px;font-size:.9em} #hint{position:absolute;left:0;right:0;bottom:3%;margin:0;text-align:center;font:italic clamp(10px,1.2vw,14px)/1.4 "Iowan Old Style",Georgia,serif;color:var(--ink);opacity:.75;pointer-events:none;transition:opacity 1.2s} #hint.gone{opacity:0} .capture #hint{display:none} </style></head><body> <div class="card" id="card"> <div id="village"></div> <div class="hud" id="clock"></div> <p id="hint">drag the sun across the sky · click anyone and anything</p> </div> <script type="module" src="./main.ts"></script></body></html>examples/village/kit.ts2.4 KBbf4888336517upstream ↗
// Shared constants and small helpers for the ink village. // The scene sets many numeric attributes; let setAttribute take numbers (the DOM stringifies them). declare global { interface Element { setAttribute(qualifiedName: string, value: string | number): void } } export const W = 960, H = 480; export const BASE = 344; // house fronts / back edge of the street export const LANE = { back: 360, mid: 366, front: 372 }; // feet lines on the street export const EDGE = 384; // canal coping top export const WATER = 400; // water surface export const SP = 0.8; // scene pen export const FS = 0.5; // figure scale (figures are drawn ~95 px tall, ground 120) export const rnd = (a, b) => a + Math.random() * (b - a); export const pick = (arr) => arr[(Math.random() * arr.length) | 0]; export const clamp = (x, a, b) => Math.max(a, Math.min(b, x)); export const lerp = (a, b, t) => a + (b - a) * t; export const smooth = (e0, e1, x) => { const t = clamp((x - e0) / (e1 - e0), 0, 1); return t * t * (3 - 2 * t); }; export const ease = (t) => smooth(0, 1, t); export const easeOut = (t) => 1 - Math.pow(1 - clamp(t, 0, 1), 3); export const oval = (cx, cy, rx, ry) => `M${(cx - rx).toFixed(2)} ${cy.toFixed(2)} a${rx} ${ry} 0 1 0 ${2 * rx} 0 a${rx} ${ry} 0 1 0 ${-2 * rx} 0Z`; // deterministic randomness for the static drawing, so the street is the same every load let seed = 11; export const srnd = (a, b) => { seed = (seed * 16807) % 2147483647; return a + ((seed - 1) / 2147483646) * (b - a); }; // colours export const hex = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16)); export const rgb = (c) => `rgb(${c.map((v) => Math.round(v)).join(',')})`; export const mix = (a, b, t) => a.map((v, i) => v + (b[i] - v) * t); export const lum = (c) => (0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]) / 255; /** Sample a cyclic colour ramp [[pos, '#hex'], ...] at u in [0,1). */ export function ramp(keys, u) { u = ((u % 1) + 1) % 1; const n = keys.length; let i = n - 1; for (let j = 0; j < n; j++) if (keys[j][0] <= u) i = j; const [p0, c0] = keys[i], [p1, c1] = keys[(i + 1) % n]; const span = (i + 1 < n ? p1 : p1 + 1) - p0; let x = u - p0; if (x < 0) x += 1; return mix(hex(c0), hex(c1), ease(x / span)); } /** Simple layered noise for organic motion (no deps). */ export const wobble = (t, k = 1) => Math.sin(t * 1.3 * k) * 0.6 + Math.sin(t * 2.7 * k + 1.7) * 0.3 + Math.sin(t * 5.1 * k + 4.1) * 0.1;examples/village/main.ts10.0 KBd95796657cdeupstream ↗
// Ink village — a Japanese street from dawn to night, drawn in pen. // Drag the sun or moon to change the time; move the pointer to make wind; // click people, windows, lanterns, the fūrin, the cat, the birds, the water. import { el, inkDefs, run, f } from '../../lib/ink.ts'; import { W, H, LANE, WATER, rnd, pick, clamp, lerp, smooth, rgb, hex, mix } from './kit.ts'; import { createSky, palette } from './sky.ts'; import { buildStreet } from './houses.ts'; import { buildCanal } from './canal.ts'; import { createKimono, createCyclist, createKid, createBoat } from './people.ts'; import { createCat, createSparrows, createSwallows, createPetals, createSmoke } from './critters.ts'; const q = new URLSearchParams(location.search); const svg = el('svg', { viewBox: `0 0 ${W} ${H}`, class: 'village', role: 'img', 'aria-label': 'An ink drawing of a Japanese street with machiya houses, a tea house and a public bath beside a canal, through day and night.' }); const ink = inkDefs(svg, 'v'); document.querySelector('#village').appendChild(svg); const defs = ink.defs; const grad = (id: string, stops: Array<[number, string, number]>, attrs: { radial?: boolean; x1?: number; x2?: number } = {}) => { const g = el(attrs.radial ? 'radialGradient' : 'linearGradient', attrs.radial ? { id } : { id, x1: attrs.x1 ?? 0, y1: 0, x2: attrs.x2 ?? 1, y2: 0 }, defs); stops.forEach(([o, c, a]) => el('stop', { offset: o, 'stop-color': c, 'stop-opacity': a }, g)); }; grad('v-beamR', [[0, '#fff1c2', 0.55], [1, '#fff1c2', 0]]); grad('v-beamL', [[0, '#fff1c2', 0], [1, '#fff1c2', 0.55]]); grad('v-cateye', [[0, '#e8ff9a', 1], [1, '#c8ff6a', 0]], { radial: true }); const layer = (parent: Element = svg, attrs: Record<string, string> = {}) => el('g', attrs, parent); const skyL = layer(); const scene = layer(svg, { filter: ink.filter }); const back = layer(scene), birdsL = layer(scene), ground = layer(scene), houses = layer(scene), front = layer(scene); const catL = layer(scene), walkers = layer(scene), canalL = layer(scene), boatL = layer(scene), willowL = layer(scene), petalL = layer(scene, { style: 'pointer-events:none' }); const glow = layer(svg, { style: 'mix-blend-mode:screen;pointer-events:none' }); // ------------------------------------------------------------------ time let tau = q.has('tau') ? +q.get('tau') : q.has('start') ? +q.get('start') : 0.66; // ?tau pins the time, ?start just sets it let scrub = null, frozenTau = q.has('tau'); const DAY_SECONDS = q.has('day') ? +q.get('day') : 180; // ?day=30 → a full cycle in 30 s // People always move at a natural pace (a sped-up gait looks fake); when a day is // compressed only the arrivals come more often, so the street stays busy. ?life= overrides. const LIFE = q.has('life') ? +q.get('life') : 1; const TRAFFIC = Math.max(1, Math.sqrt(180 / DAY_SECONDS)); const card = document.querySelector<HTMLElement>('#card')!; if (q.has('capture')) document.body.classList.add('capture'); // ------------------------------------------------------------------ wind from the pointer let wind = 0.3, windTarget = 0.3, lastX = null, lastT = 0; svg.addEventListener('pointermove', (e) => { const now = performance.now(); if (lastX !== null && !svg.classList.contains('scrubbing')) windTarget = clamp(windTarget + ((e.clientX - lastX) / Math.max(8, now - lastT)) * 0.8, -2.4, 2.4); lastX = e.clientX; lastT = now; }); const on = (node, fn) => node.addEventListener('pointerdown', (e) => { e.stopPropagation(); fn(e); hint.done(); }); const toSvg = (e) => { const p = svg.createSVGPoint(); p.x = e.clientX; p.y = e.clientY; return p.matrixTransform(svg.getScreenCTM().inverse()); }; // ------------------------------------------------------------------ world const sky = createSky(svg, skyL, defs, { onScrub: (v) => { scrub = v; if (v !== null) { tau = v; frozenTau = false; hint.done(); } }, onShoot: () => palette(tau).night > 0.4, }); const street = buildStreet({ back, houses, front, glow }, defs); const canal = buildCanal({ ground, canalL, willowL, glow }, defs); const smoke = createSmoke(back, street.chimney); const sparrows = createSparrows(birdsL, { wireY: street.wireY }); const swallows = createSwallows(birdsL); const petals = createPetals(petalL, { blossoms: street.blossoms, canal }); const cat = createCat(catL, glow, { x: 548, y: 330 }); const boat = createBoat(boatL, glow, { onRipple: (x, y) => canal.ring(x, y, 2) }); // reflections in the water under every light source street.windows.forEach((w) => canal.addRefl(() => w.lit, (w.x0 + w.x1) / 2, Math.min(40, (w.x1 - w.x0) * 0.8))); street.lanterns.forEach((l) => canal.addRefl(() => smooth(l.thr, l.thr + 0.2, P.lamp), l.x, 8)); canal.addRefl(() => smooth(0.2, 0.45, P.lamp), 446, 14); // interactions on the scenery street.lanterns.forEach((l) => { l.grp.style.cursor = 'pointer'; on(l.grp, () => l.poke()); }); street.norens.forEach((n) => { n.grp.style.cursor = 'pointer'; on(n.grp, () => n.poke()); }); const hits = layer(scene); const hitPath = (d, title, fn) => { const n = el('path', { d, fill: 'transparent', style: 'cursor:pointer' }, hits); el('title', {}, n).textContent = title; on(n, fn); return n; }; hitPath(street.shoji.hit, 'Knock on the window', () => street.shoji.poke()); hitPath('M402 202 L422 202 L422 236 L402 236Z', 'Ring the wind chime', () => street.furin.poke()); let shake = 0; street.canopy.style.cursor = 'pointer'; on(street.canopy, () => { shake = 1; petals.burst(46); }); on(sparrows.hit, () => sparrows.flush()); on(cat.hit, () => cat.poke()); on(boat.g, () => boat.poke()); willowL.style.cursor = 'pointer'; on(willowL, () => canal.willowPoke()); const waterHit = el('rect', { x: 0, y: WATER, width: W, height: H - WATER, fill: 'transparent', style: 'cursor:pointer' }, canalL); on(waterHit, (e) => { const p = toSvg(e); canal.poke(p.x, p.y); }); canalL.insertBefore(waterHit, canalL.children[2] || null); // ------------------------------------------------------------------ villagers const people = []; const spawn = { kimono: 0, bike: 7, kid: 4 }; function addPerson(kind: 'kimono' | 'bike' | 'kid', x?: number) { const dir = Math.random() < 0.5 ? 1 : -1; const sx = x ?? (dir > 0 ? -60 : W + 60); let p; if (kind === 'kimono') p = createKimono(walkers, glow, { dir, x: sx, y: LANE.back + rnd(-1, 1), lantern: P.lamp > 0.5 }); if (kind === 'bike') p = createCyclist(walkers, glow, { dir, x: sx, y: LANE.front + rnd(-1, 1) }); if (kind === 'kid') p = createKid(walkers, glow, { dir, x: sx, y: LANE.mid + rnd(-1, 1) }); on(p.g, () => { p.poke(); if (p.kind === 'bike') setTimeout(() => sparrows.flush(), 150); }); people.push(p); } // ------------------------------------------------------------------ hud const clock = document.querySelector('#clock'), hintN = document.querySelector('#hint'); const hint = { shown: true, done() { if (this.shown) { this.shown = false; hintN.classList.add('gone'); } } }; setTimeout(() => hint.done(), 14000); const period = (h) => (h < 4 ? '深夜' : h < 6 ? '夜明け' : h < 10 ? '朝' : h < 15 ? '昼' : h < 17.5 ? '午後' : h < 19.5 ? '夕暮れ' : '夜'); // ------------------------------------------------------------------ frame let P = palette(tau); let started = false; run((t, dt) => { dt = dt || 1 / 60; if (scrub === null && !frozenTau) tau = (tau + dt / DAY_SECONDS) % 1; P = palette(tau); svg.style.color = rgb(P.ink); svg.style.setProperty('--paper', rgb(P.paper)); card.style.setProperty('--ink', rgb(P.ink)); windTarget = lerp(windTarget, 0.3 + 0.25 * Math.sin(t * 0.21) + 0.15 * Math.sin(t * 0.67), 0.012); wind = lerp(wind, windTarget, 0.05); sky.draw(tau, t, dt, P, wind); street.applyRed(P); const sinceDusk = (tau - 0.75 + 1) % 1; street.windows.forEach((w) => { let lit = smooth(w.thr, w.thr + 0.25, P.lamp); if (w.lateOff < 9 && sinceDusk > w.lateOff - 0.75 && sinceDusk < 0.5) lit = 0; w.lit = lerp(w.lit, lit, 0.08); w.n.style.fill = rgb(mix(P.paper, mix(hex('#ffd58a'), hex('#f0a24e'), w.warmth), w.lit * 0.92)); w.glow.setAttribute('opacity', f(w.lit * 0.8)); }); const L = street.lamp, lampOn = smooth(0.2, 0.45, P.lamp); L.node.style.fill = rgb(mix(P.paper, hex('#fff1c9'), lampOn)); L.cone.setAttribute('opacity', f(lampOn * 0.75)); L.glow.setAttribute('opacity', f(lampOn)); street.norens.forEach((n) => n.draw(t, dt, wind, tau, P)); street.lanterns.forEach((l) => l.draw(t, dt, wind, P)); street.furin.draw(t, dt, wind); street.shoji.draw(t, dt, P); shake = Math.max(0, shake - dt * 1.5); street.canopy.setAttribute('transform', `translate(${f(Math.sin(t * 40) * shake * 2.4 + wind * 0.9)} ${f(Math.cos(t * 31) * shake * 1.2)})`); smoke.draw(t, dt, P, wind, tau); sparrows.draw(t, dt, P); swallows.draw(t, dt, P); petals.draw(t, dt, P, wind); cat.draw(t, dt, P); canal.draw(t, dt, P, wind, null, tau, lampOn); boat.draw(t, dt * LIFE, P, wind); // villagers: spawn on their own schedules, draw back-to-front if (!started) { started = true; addPerson('kimono', 300); addPerson('kimono', 760); addPerson('bike', 560); } const dayish = tau > 0.28 && tau < 0.72, lateNight = tau > 0.96 || tau < 0.22; for (const k in spawn) { spawn[k] -= dt * TRAFFIC; if (spawn[k] < 0) { if (k === 'kimono') { spawn[k] = rnd(10, 18); if (!lateNight || Math.random() < 0.3) addPerson('kimono'); } if (k === 'bike') { spawn[k] = rnd(9, 16); if (!lateNight) addPerson('bike'); } if (k === 'kid') { spawn[k] = rnd(14, 24); if (dayish) addPerson('kid'); } } } for (let i = people.length - 1; i >= 0; i--) { const p = people[i]; p.draw(t, dt * LIFE, P, wind); if (p.done) { p.remove(); people.splice(i, 1); } else if (p.ringing && Math.random() < dt * 4) sparrows.flush(); } people.slice().sort((a, b) => a.y - b.y).forEach((p) => walkers.appendChild(p.g)); // clock const hrs = tau * 24, h = Math.floor(hrs), m = Math.floor((hrs - h) * 60); clock.innerHTML = `<b>${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}</b> <span>${period(hrs)}</span>`; }); (window as unknown as { __village: unknown }).__village = { addPerson, setTau: (v) => { tau = v; frozenTau = true; }, get tau() { return tau; }, people, sparrows, cat, boat, canal, street, petals };examples/village/people.ts31 KB0513c9f9fb09upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
examples/village/sky.ts9.9 KBc99b7615ca4eupstream ↗
// Sky, sun, moon, stars and the day/night palette. // Time of day τ ∈ [0,1): 0 midnight, 0.25 dawn, 0.5 noon, 0.75 dusk. import { el, pen, shape, blot, f, pt, PAPER } from '../../lib/ink.ts'; import { W, SP, rnd, srnd, clamp, lerp, smooth, ramp, rgb, hex, mix, lum, oval } from './kit.ts'; const SKY_TOP = [[0, '#0d1222'], [0.19, '#131a30'], [0.235, '#3d4066'], [0.27, '#cfd8e2'], [0.33, '#f3f2ee'], [0.5, '#f6f5f1'], [0.68, '#f3eee4'], [0.735, '#e3c6a6'], [0.762, '#5a5279'], [0.80, '#1b2140'], [0.86, '#0d1222']]; const SKY_BOT = [[0, '#1a2240'], [0.19, '#283050'], [0.235, '#d49884'], [0.27, '#f3d0b3'], [0.33, '#faf6ee'], [0.5, '#fcfbf7'], [0.68, '#f9efdc'], [0.735, '#f0a379'], [0.762, '#d47f68'], [0.80, '#383a60'], [0.86, '#1a2240']]; const PAPERS = [[0, '#1a2036'], [0.19, '#1f263e'], [0.235, '#4a4561'], [0.27, '#ede4d8'], [0.33, '#fbf8f1'], [0.5, '#fdfcf8'], [0.68, '#faf4e8'], [0.735, '#f0dbc4'], [0.756, '#5d5571'], [0.80, '#262c48'], [0.86, '#1a2036']]; const INK_DARK = hex('#1c1c1c'), INK_LIGHT = hex('#efe6cf'); export function palette(tau) { const top = ramp(SKY_TOP, tau), bot = ramp(SKY_BOT, tau), paper = ramp(PAPERS, tau); const L = lum(paper); const inkT = smooth(0.56, 0.36, L); return { top, bot, paper, ink: mix(INK_DARK, INK_LIGHT, inkT), inkT, lamp: smooth(0.78, 0.4, L), // how dark it is for lamps (windows add their own threshold) night: smooth(0.42, 0.1, lum(top)), // stars, moon glow, fireflies sunset: Math.max(smooth(0.67, 0.735, tau) * smooth(0.79, 0.745, tau), smooth(0.215, 0.245, tau) * smooth(0.3, 0.26, tau)), }; } const sunArc = (u) => [40 + 880 * u, 300 - 236 * Math.sin(Math.PI * u)]; const moonArc = (u) => [60 + 840 * u, 290 - 205 * Math.sin(Math.PI * u)]; const SUN_SPAN = [0.225, 0.55], MOON_SPAN = [0.775, 0.45]; export function createSky(svg, root, defs, { onScrub, onShoot }) { // gradient sky const grad = el('linearGradient', { id: 'v-sky', x1: 0, y1: 0, x2: 0, y2: 1 }, defs); const s0 = el('stop', { offset: 0 }, grad), s1 = el('stop', { offset: 1 }, grad); const glowSun = el('radialGradient', { id: 'v-sunglow' }, defs); el('stop', { offset: 0, 'stop-color': '#ffd9a0', 'stop-opacity': 0.55 }, glowSun); el('stop', { offset: 1, 'stop-color': '#ffd9a0', 'stop-opacity': 0 }, glowSun); const glowMoon = el('radialGradient', { id: 'v-moonglow' }, defs); el('stop', { offset: 0, 'stop-color': '#e9e4ff', 'stop-opacity': 0.35 }, glowMoon); el('stop', { offset: 1, 'stop-color': '#e9e4ff', 'stop-opacity': 0 }, glowMoon); const g = el('g', {}, root); el('rect', { x: -20, y: -20, width: W + 40, height: 520, fill: 'url(#v-sky)' }, g); // stars const starG = el('g', {}, g); const stars = Array.from({ length: 90 }, () => { const x = srnd(0, W), y = srnd(6, 250), r = srnd(0.35, 1.05); return { n: el('circle', { cx: f(x), cy: f(y), r: f(r), fill: '#f5efda' }, starG), ph: srnd(0, 6), sp: srnd(0.6, 2.4), big: r > 0.9, spark: null as SVGPathElement | null }; }); stars.filter((s) => s.big).forEach((s) => { const x = +s.n.getAttribute('cx'), y = +s.n.getAttribute('cy'); s.spark = el('path', { d: `M${x - 2.6} ${y} L${x + 2.6} ${y} M${x} ${y - 2.6} L${x} ${y + 2.6}`, stroke: '#f5efda', 'stroke-width': 0.35, opacity: 0.6 }, starG); }); const shoots = []; // sun & moon (draggable) const sunG = el('g', { class: 'drag', style: 'cursor:grab' }, g); const sunGlow = el('circle', { r: 70, fill: 'url(#v-sunglow)' }, sunG); const sunDisk = el('circle', { r: 21, stroke: 'currentColor', 'stroke-width': SP }, sunG); el('title', {}, sunG).textContent = 'Drag the sun to change the time'; const moonG = el('g', { class: 'drag', style: 'cursor:grab' }, g); el('circle', { r: 60, fill: 'url(#v-moonglow)' }, moonG); const moonDisk = el('path', { fill: '#f3ecd6', stroke: '#f3ecd6', 'stroke-width': 0.6 }, moonG); const moonShade = el('path', { fill: 'none', stroke: '#cfc6ad', 'stroke-width': 0.5, opacity: 0.7 }, moonG); el('title', {}, moonG).textContent = 'Drag the moon to change the time'; // mist bands (suyari-gasumi) drifting in the day sky const mist = el('g', {}, g); const bands = [[120, 92, 150], [520, 64, 190], [760, 120, 130], [330, 140, 100]].map(([x, y, w]) => ({ x, y, w, v: rnd(1.2, 2.6), n: pen(mist, SP * 0.75) })); // Japanese cloud strokes: long horizontal lines that curl into small spirals at the ends const cloudD = (x, y, w) => { const curlR = (cx, cy, s) => `M${f(cx)} ${f(cy)} q${5 * s} 0 ${5 * s} -4 q0 -3.2 ${-3.2 * s} -3.2 q-2.2 0 -2.2 2.2 q0 1.4 1.4 1.4`; return `M${f(x)} ${f(y)} L${f(x + w)} ${f(y)} ${curlR(x + w, y, 1)} ${curlR(x, y, -1)} ` + `M${f(x + w * 0.18)} ${f(y - 7)} L${f(x + w * 0.66)} ${f(y - 7)} ${curlR(x + w * 0.66, y - 7, 1)} ` + `M${f(x + w * 0.42)} ${f(y + 6.5)} L${f(x + w * 0.92)} ${f(y + 6.5)} ${curlR(x + w * 0.42, y + 6.5, -1)}`; }; // far hills and a pagoda, in diluted ink const far = el('g', { opacity: 0.42 }, g); pen(far, SP * 0.8).setAttribute('d', 'M0 262 Q80 238 170 222 Q240 206 300 214 Q360 222 420 208 Q470 196 520 188 Q600 176 660 198 Q720 218 790 206 Q860 192 960 214'); pen(far, SP * 0.55).setAttribute('d', 'M140 228 q20 -6 40 -4 M300 216 q16 -2 30 2 M560 186 q26 -4 44 4 M820 202 q18 -4 32 0'); drawPagoda(far, 640, 236); // dragging: pointer x along the arc → time let drag = null; const toSvg = (e) => { const p = svg.createSVGPoint(); p.x = e.clientX; p.y = e.clientY; return p.matrixTransform(svg.getScreenCTM().inverse()); }; const start = (kind) => (e) => { e.preventDefault(); e.stopPropagation(); drag = kind; svg.setPointerCapture?.(e.pointerId); svg.classList.add('scrubbing'); }; sunG.addEventListener('pointerdown', start('sun')); moonG.addEventListener('pointerdown', start('moon')); svg.addEventListener('pointermove', (e) => { if (!drag) return; const p = toSvg(e); if (drag === 'sun') onScrub(SUN_SPAN[0] + SUN_SPAN[1] * clamp((p.x - 40) / 880, 0, 1)); else onScrub((MOON_SPAN[0] + MOON_SPAN[1] * clamp((p.x - 60) / 840, 0, 1)) % 1); }); const end = () => { if (drag) { drag = null; svg.classList.remove('scrubbing'); onScrub(null); } }; svg.addEventListener('pointerup', end); svg.addEventListener('pointercancel', end); // night sky click → shooting star const skyHit = el('rect', { x: 0, y: 0, width: W, height: 160, fill: 'transparent' }, g); skyHit.addEventListener('pointerdown', (e) => { if (onShoot()) { const p = toSvg(e); shoot(p.x, p.y); } }); g.insertBefore(skyHit, sunG); function shoot(x, y) { shoots.push({ x: x - 30, y: y - 18, t: 0, dir: Math.random() < 0.5 ? -1 : 1, n: el('path', { stroke: '#fff6dc', 'stroke-width': 0.9, 'stroke-linecap': 'round', fill: 'none' }, starG) }); } return { shoot, draw(tau, t, dt, P, wind) { s0.setAttribute('stop-color', rgb(P.top)); s1.setAttribute('stop-color', rgb(P.bot)); starG.setAttribute('opacity', f(P.night)); if (P.night > 0.01) stars.forEach((s) => { const tw = 0.55 + 0.45 * Math.sin(t * s.sp + s.ph); s.n.setAttribute('opacity', f(tw)); if (s.spark) s.spark.setAttribute('opacity', f(tw * 0.7)); }); if (P.night > 0.6 && Math.random() < dt * 0.04) shoot(rnd(100, 860), rnd(30, 110)); for (let i = shoots.length - 1; i >= 0; i--) { const s = shoots[i]; s.t += dt; const u = s.t / 0.9, x = s.x + s.dir * 120 * u, y = s.y + 60 * u; s.n.setAttribute('d', `M${f(x)} ${f(y)} L${f(x - s.dir * 34 * (1 - u))} ${f(y - 17 * (1 - u))}`); s.n.setAttribute('opacity', f(Math.sin(Math.PI * Math.min(1, u)))); if (u >= 1) { s.n.remove(); shoots.splice(i, 1); } } // sun const su = (tau - SUN_SPAN[0]) / SUN_SPAN[1]; if (su > -0.05 && su < 1.05) { const [x, y] = sunArc(clamp(su, 0, 1)); sunG.setAttribute('transform', `translate(${f(x)} ${f(y + (su < 0 || su > 1 ? 30 : 0))})`); sunG.style.display = ''; sunDisk.setAttribute('fill', rgb(mix(hex('#fbf3df'), hex('#df5a3a'), P.sunset))); sunGlow.setAttribute('opacity', f(0.35 + 0.65 * P.sunset)); } else sunG.style.display = 'none'; // moon (waxing crescent drawn with two arcs) const mu = (((tau - MOON_SPAN[0]) % 1) + 1) % 1 / MOON_SPAN[1]; if (mu <= 1.02) { const [x, y] = moonArc(clamp(mu, 0, 1)); moonG.setAttribute('transform', `translate(${f(x)} ${f(y)}) rotate(-24)`); moonG.style.display = ''; moonG.setAttribute('opacity', f(smooth(0, 0.08, mu) * smooth(1.02, 0.94, mu))); const r = 15; moonDisk.setAttribute('d', `M0 ${-r} A${r} ${r} 0 1 1 0 ${r} A${r * 0.62} ${r} 0 1 0 0 ${-r}Z`); moonShade.setAttribute('d', `M3 -6 a2.4 1.8 0 1 0 0.1 0 M8 4 a1.6 1.3 0 1 0 0.1 0`); } else moonG.style.display = 'none'; // mist bands — strongest in the morning mist.setAttribute('opacity', f(0.75 - 0.45 * P.night)); bands.forEach((b) => { b.x += (b.v + wind * 3) * dt; if (b.x > W + 40) b.x = -b.w - 40; if (b.x < -b.w - 60) b.x = W + 30; b.n.setAttribute('d', cloudD(b.x, b.y, b.w)); }); }, }; } function drawPagoda(g, cx, baseY) { // five tiers, each a sweeping roof with a small body under it, then the sōrin spire let y = baseY; for (let i = 0; i < 5; i++) { const w = 36 - i * 4.2, bodyH = 9 - i * 0.6; shape(g, SP * 0.75).setAttribute('d', `M${cx - w * 0.42} ${y} L${cx + w * 0.42} ${y} L${cx + w * 0.42} ${y - bodyH} L${cx - w * 0.42} ${y - bodyH}Z`); pen(g, SP * 0.5).setAttribute('d', `M${cx - w * 0.18} ${y} L${cx - w * 0.18} ${y - bodyH} M${cx + w * 0.18} ${y} L${cx + w * 0.18} ${y - bodyH}`); y -= bodyH; shape(g, SP * 0.75).setAttribute('d', `M${cx - w} ${y + 1} Q${cx - w * 0.6} ${y - 1} ${cx - w * 0.35} ${y - 5} L${cx + w * 0.35} ${y - 5} Q${cx + w * 0.6} ${y - 1} ${cx + w} ${y + 1} Q${cx} ${y - 2} ${cx - w} ${y + 1}Z`); y -= 5; } pen(g, SP * 0.8).setAttribute('d', `M${cx} ${y} L${cx} ${y - 26}`); pen(g, SP * 0.5).setAttribute('d', Array.from({ length: 6 }, (_, k) => `M${cx - 2.6} ${y - 4 - k * 3} L${cx + 2.6} ${y - 4 - k * 3}`).join(' ')); }examples/village/tsconfig.json143 B93cf8ea6a9ddupstream ↗
{ "extends": "../../tsconfig.json", "compilerOptions": { "strict": false, "noImplicitAny": false }, "include": ["./*.ts", "../../lib"] }examples/walker/index.html786 B02f1a3855fbeupstream ↗
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Walker · line-art-animation</title> <style> html, body { margin: 0; height: 100%; background: #ebe8e2; } body { display: grid; place-items: center; } .card { width: min(92vw, calc((100vh - 48px) * 2)); aspect-ratio: 2 / 1; border-radius: 16px; overflow: hidden; background: #fdfcf8; box-shadow: 0 0 0 1px rgba(40, 34, 26, .10), 0 18px 50px -18px rgba(40, 34, 26, .35); } #stage, #stage svg { display: block; width: 100%; height: 100%; } #stage svg .pp { fill: var(--paper, #fdfdfc); } </style> </head> <body> <div class="card"><div id="stage"></div></div> <script type="module" src="./walker.ts"></script> </body> </html>examples/walker/walker.ts6.8 KB8c8175ad7109upstream ↗
// A man with a briefcase walks across the card. Click him to tip his hat; // move the pointer to blow his scarf. ~150 lines: the smallest complete example // of the library — gait, open-stroke limbs, clothing drawn around the legs, // springs for things that swing, a reaction to a click. import { el, pen, shape, blot, paint, limb, shoe, place, inkDefs, run, f, pt, PEN, PAPER, type Vec } from '../../lib/ink.ts'; import { gait } from '../../lib/gait.ts'; import { spring, pendulum, pointerWind, ease, clamp } from '../../lib/motion.ts'; const W = 480, H = 240, GROUND = 196, SCALE = 1.25; const svg = el('svg', { viewBox: `0 0 ${W} ${H}`, role: 'img', 'aria-label': 'Line drawing of a man walking with a briefcase' }); const { filter } = inkDefs(svg, 'w'); document.querySelector('#stage')!.appendChild(svg); const scene = el('g', { filter }, svg); // --- a little street: kerb, paving, a lamp post pen(scene, 0.9).setAttribute('d', `M0 ${GROUND} L${W} ${GROUND} M0 ${GROUND + 9} L${W} ${GROUND + 9}`); pen(scene, 0.55).setAttribute('d', Array.from({ length: 16 }, (_, i) => `M${i * 32 + 10} ${GROUND} l0 9`).join(' ')); shape(scene, 0.9).setAttribute('d', `M383 ${GROUND} L385 70 L389 70 L391 ${GROUND}Z`); shape(scene, 0.9).setAttribute('d', 'M377 70 L397 70 L394 58 L380 58Z'); pen(scene, 0.6).setAttribute('d', 'M381 64 L393 64 M387 58 L387 52'); // --- the figure, back to front. Everything is in figure space (feet on y 120). const fig = el('g', { style: 'cursor:pointer' }, scene); const farArm = limb(fig, 3.6); const legs = [limb(fig, 4.2), limb(fig, 4.2)]; const shoes = [blot(fig), blot(fig)]; const coat = shape(fig); const coatSeam = pen(fig, PEN * 0.6); const scarfTail = paint(fig, '#b3412d', PEN * 0.8); const head = el('ellipse', { rx: 3.6, ry: 4.6, fill: PAPER, stroke: 'currentColor', 'stroke-width': PEN }, fig); const hat = blot(fig); const scarf = paint(fig, '#b3412d', PEN * 0.8); const nearArm = limb(fig, 3.6); const caseG = el('g', {}, fig); const briefcase = paint(caseG, '#6b4a32', PEN * 0.8); const handle = pen(caseG, PEN * 0.7); const walk = gait({ kind: 'walk' }); const wind = pointerWind(svg, 0.2); const armSwing = [spring(60, 9), spring(60, 9)]; const caseSwing = pendulum(14, 1.8); const tail = spring(30, 4); let phase = 0, x = 120, tipT = -1; fig.addEventListener('pointerdown', () => { if (tipT < 0) tipT = 0; }); run((t, dt) => { wind.step(t); // tipping the hat: slow to a stop, raise the hand, lift the hat, walk on let tip = 0; if (tipT >= 0) { tipT += dt; tip = tipT < 0.35 ? ease(tipT / 0.35) : tipT < 1.2 ? 1 : 1 - ease((tipT - 1.2) / 0.4); if (tipT > 1.6) tipT = -1; } const go = 1 - tip * 0.85; phase += (dt / walk.period) * go; x += walk.speed * SCALE * dt * go; if (x > W + 50) x = -50; place(fig, x, GROUND, 1, SCALE); const p = walk.pose(phase, go); const b = p.bob; // legs; the leading leg is drawn on top p.feet.forEach((fo, i) => { legs[i].draw([p.hip, fo.knee, fo.ankle], [0.3, 0.8]); shoe(shoes[i], fo.ankle, fo.pitch); }); fig.insertBefore(legs[p.front].g, coat); fig.insertBefore(shoes[p.front], coat); // coat: drawn around the forward knee, so the hem opens and closes with the stride const kF = p.feet[p.front].knee, aF = p.feet[p.front].ankle; const sh: Vec = [41, 41 + b], hemY = 92; const fx = Math.max(kF[0] + 2.4, 46.4); coat.setAttribute('d', `M${f(sh[0] - 6)} ${f(sh[1] + 1)} Q${f(sh[0] - 1)} ${f(sh[1] - 2.4)} ${f(sh[0] + 5)} ${f(sh[1] + 1)} L${f(fx - 0.6)} ${f(70 + b)} Q${f(fx)} ${f(82 + b * 0.5)} ${f(Math.max(fx, aF[0] - 4))} ${hemY} L${f(30.6)} ${hemY + 1} L${f(33.2)} ${f(70 + b)}Z`); coatSeam.setAttribute('d', `M${f(sh[0] + 2.6)} ${f(sh[1] + 4)} L${f(sh[0] + 3.8)} ${f(66 + b)}`); // head, hat (lifts when tipped), scarf tail streaming in the wind const hc: Vec = [42.6, 31.6 + b]; head.setAttribute('cx', f(hc[0])); head.setAttribute('cy', f(hc[1])); const lift = tip * 5; hat.setAttribute('d', `M${f(hc[0] - 6.4)} ${f(hc[1] - 3.6 - lift)} L${f(hc[0] + 6.6)} ${f(hc[1] - 3.6 - lift)} Q${f(hc[0] + 4.4)} ${f(hc[1] - 5 - lift)} ${f(hc[0] + 4)} ${f(hc[1] - 8 - lift)} Q${f(hc[0])} ${f(hc[1] - 11 - lift)} ${f(hc[0] - 3.8)} ${f(hc[1] - 8 - lift)} Q${f(hc[0] - 4.2)} ${f(hc[1] - 5 - lift)} ${f(hc[0] - 6.4)} ${f(hc[1] - 3.6 - lift)}Z`); scarf.setAttribute('d', `M${f(hc[0] - 4.6)} ${f(hc[1] + 4.6)} Q${f(hc[0])} ${f(hc[1] + 8.4)} ${f(hc[0] + 4)} ${f(hc[1] + 4.8)} L${f(hc[0] + 4.4)} ${f(hc[1] + 7.6)} Q${f(hc[0])} ${f(hc[1] + 11)} ${f(hc[0] - 4.8)} ${f(hc[1] + 7.4)}Z`); const flow = tail.step(-6 - walk.speed * 0.08 * go - wind.value * 5 + Math.sin(t * 9) * 0.8, dt); scarfTail.setAttribute('d', `M${f(hc[0] - 3.6)} ${f(hc[1] + 6)} Q${f(hc[0] - 6 + flow * 0.4)} ${f(hc[1] + 9)} ${f(hc[0] - 4 + flow)} ${f(hc[1] + 16 + flow * 0.2)} L${f(hc[0] - 1 + flow * 0.9)} ${f(hc[1] + 16.6 + flow * 0.2)} Q${f(hc[0] - 3 + flow * 0.3)} ${f(hc[1] + 10)} ${f(hc[0] - 0.8)} ${f(hc[1] + 7.4)}Z`); // arms swing opposite the legs, through springs so they lag and settle const legSwing = (p.feet[0].ankle[0] - 40) / (walk.stride / 2); // -1..1, near leg const farA = armSwing[0].step(-legSwing * 16 * go, dt) * Math.PI / 180; const nearA = armSwing[1].step(legSwing * 14 * go, dt) * Math.PI / 180; const shF: Vec = [sh[0] - 1, sh[1] + 2], shN: Vec = [sh[0] + 1.6, sh[1] + 2.4]; const elbF: Vec = [shF[0] + 17 * Math.sin(farA), shF[1] + 17 * Math.cos(farA)]; farArm.draw([shF, elbF, [elbF[0] + 16 * Math.sin(farA + 0.25), elbF[1] + 16 * Math.cos(farA + 0.25)]], [0.2, 0.5]); let hand: Vec; if (tip > 0.01) { // near arm goes to the hat brim const target: Vec = [hc[0] + 4, hc[1] - 4 - lift]; const mid = lerpP(shN, target, 0.5); const elb: Vec = [mid[0] + 7 * tip, mid[1] + 3]; hand = lerpP([shN[0] + 17 * Math.sin(nearA) + 16 * Math.sin(nearA + 0.1), shN[1] + 33], target, tip); nearArm.draw([shN, lerpP([shN[0] + 17 * Math.sin(nearA), shN[1] + 17], elb, tip), hand], [0.2, 0.4]); } else { const elb: Vec = [shN[0] + 17 * Math.sin(nearA), shN[1] + 17 * Math.cos(nearA)]; hand = [elb[0] + 16 * Math.sin(nearA + 0.1), elb[1] + 16 * Math.cos(nearA + 0.1)]; nearArm.draw([shN, elb, hand], [0.2, 0.4]); } // briefcase hangs from the near hand (or rests on the ground-side when tipping) const accel = Math.cos(2 * Math.PI * phase * 2) * 1.6 * go; const ca = caseSwing.step(-accel - wind.value * 0.3, dt); const ch: Vec = tip > 0.01 ? [shN[0] + 6, shN[1] + 34] : hand; caseG.setAttribute('transform', `rotate(${f(ca * 57.3)} ${pt(ch)})`); handle.setAttribute('d', `M${f(ch[0] - 2.4)} ${f(ch[1] + 2.4)} Q${pt(ch)} ${f(ch[0] + 2.4)} ${f(ch[1] + 2.4)}`); briefcase.setAttribute('d', `M${f(ch[0] - 8)} ${f(ch[1] + 2.4)} L${f(ch[0] + 8)} ${f(ch[1] + 2.4)} L${f(ch[0] + 8)} ${f(ch[1] + 13)} L${f(ch[0] - 8)} ${f(ch[1] + 13)}Z`); }); function lerpP(a: Vec, b: Vec, t: number): Vec { t = clamp(t, 0, 1); return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]; }index.html1.1 KBca39af2fbc2bupstream ↗
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>line-art-animation</title> <style> body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #ebe8e2; color: #1c1c1c; font: 15px/1.6 ui-serif, "Iowan Old Style", Georgia, serif; } main { width: min(560px, 90vw); } h1 { font-size: 20px; font-weight: 600; margin: 0 0 4px; } p { margin: 0 0 20px; color: #5a554d; } a { display: block; padding: 14px 0; border-top: 1px solid rgba(28, 28, 28, .12); color: inherit; text-decoration: none; } a:hover span { text-decoration: underline; } small { display: block; color: #7a746a; font-size: 13px; } </style> </head> <body> <main> <h1>line-art-animation</h1> <p>Examples built with the library in <code>lib/</code>.</p> <a href="examples/walker/"><span>Walker</span><small>One figure: gait, open-stroke limbs, springs, a click reaction. About 150 lines.</small></a> <a href="examples/village/"><span>Village</span><small>A full scene: day/night cycle, lit windows, villagers, wind, a dozen interactions.</small></a> </main> </body> </html>lib/daynight.ts3.5 KBbbe9980a7954upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
lib/gait.ts6.2 KB96cdccc22b02upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
lib/ink.ts9.6 KB071a0213e10bupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
lib/motion.ts3.6 KB079f8624ed08upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
LICENSE1.0 KBab4bb8daa90dupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
media/day.png562 KBb30658204e55upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
media/night.png692 KB0587a07c47a5upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
media/village.gif5.6 MB005e672b09cdupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
media/walker.gif242 KBd24bba200cf6upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
package-lock.json35 KB786e60a4ac1dupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
package.json515 Bcac3eaa79203upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
tsconfig.json421 B866c628cad20upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
vite.config.ts390 Bb324c688f2a6upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
Plain-text copy, no login: /skill-bundles/jdhruv14-line-art-animation.md

