Solarpunk Lizards is a single web page: a stilt town of cabins, glass domes and windmills on a cliff at sunset, with axolotls, cats, ghosts, fireflies and blimps living in it. Almost everything moves, and almost everything reacts when you hover it. Its author says it was drawn with Opus 5.5 in pure JavaScript. There is no framework, no SVG, no WebGL, and no build step: one <canvas>, about thirty plain script files, and the Canvas 2D API.
I downloaded the scripts and read them end to end, because I wanted to know why it feels so much more alive than most web animation, including my own. This post is what I found, written as a playbook I can return to the next time I build something interactive. The code samples are my own minimal versions of each idea, not the site's source. The site publishes no licence, so study it, don't copy it.
At the end I show how I moved four of these ideas into the brand monkey on this site, which is an SVG with CSS expressions rather than a canvas.
How to study a site like this#
Before the techniques, the method, because it is reusable.
- Fetch the HTML and list its scripts.
curl -sSL <url> -o index.html, then grep forsrc=. Unbundled sites like this one hand you the whole architecture in the order the scripts load. - Read the comments in the HTML first. This page has a block comment listing every layer's z-index and which file owns it. That one comment is the map of the whole project.
- Read the engine before the content. Here, three small files (
ink.js,stage.js,kit.js, about 35 KB together) define everything; the other twenty-odd files are scenery written against them. - Separate code from data. About 4.2 MB of the 4.8 MB download is generated vector data for the treetops (written by a tracing tool, marked "do not edit by hand"). The hand-written drawing code is about 600 KB.
- Look for developer switches. The project reads URL parameters such as
?hits(outline every hover area),?only=and?skip=(isolate layers),?still(render one settled frame for screenshots),?t=12(start the clock at 12 seconds) and?profile(per-layer draw cost). These tell you what the author needed in order to work, which is often the most transferable lesson of all.
1. One fixed artboard, scaled to the screen#
All drawing happens in a single coordinate space, the size of the original drawing (1601 × 2000 units). Nothing in the scene ever thinks about screen pixels. The stage computes one scale factor and sets it as the canvas transform before each draw:
const ART_W = 1601, ART_H = 2000;
function layout(canvas, ctx) {
const dpr = Math.min(devicePixelRatio || 1, 2); // cap: 3× screens cost 2.25× the pixels of 2×
const s = Math.min(innerWidth / ART_W, innerHeight / ART_H);
canvas.style.width = innerWidth + 'px';
canvas.style.height = innerHeight + 'px';
canvas.width = Math.round(innerWidth * dpr);
canvas.height = Math.round(innerHeight * dpr);
const k = canvas.width / (innerWidth / s); // artboard units → device pixels
ctx.setTransform(k, 0, 0, k, 0, 0);
ctx.lineJoin = ctx.lineCap = 'round'; // resizing a canvas resets its state
}Three details matter:
- Device pixel ratio, capped at 2. This is why it looks sharp on a retina screen without burning a phone's GPU.
- Fill the window, don't letterbox. When the window is wider than the drawing, the stage widens the visible "world" and draws mirrored copies of the scenery past the artboard's edges, flipped every other copy so the seams match. When it is taller, it shows more sky. The composition stays centred and nothing gets black bars.
- A crop, not a resize. A config value picks which rectangle of the artboard is the "view"; the drawing itself is always laid out on the whole artboard. You can reframe the scene without moving a single shape.
2. A layer engine in about 250 lines#
Every visible thing is a layer: a plain object the stage sorts by z and draws each frame.
const layers = [];
function layer(def) {
const L = Object.assign({ z: 0, hover: 0, hovered: false, since: 0, still: false }, def);
layers.push(L);
return L;
}
// a layer:
layer({
id: 'windmill', z: 30,
hit: windmillOutline, // Path2D or (x, y) => boolean
update(dt, t, L) { /* advance state */ },
draw(ctx, t, L) { /* paint, reading L.hover */ },
onEnter(L) { /* one-shot reaction */ },
onTap(x, y, L) { /* touch / click */ },
});The scene files never touch the loop, the pointer or the canvas size. They only declare layers. This is what lets one project grow to thirty files without becoming a tangle: each file owns a few layers and a few z-values, and the HTML comment records who owns what.
The loop itself is short:
Two engineering habits in it are worth copying everywhere:
- Clamp
dt.dt = Math.min(0.05, elapsed). A tab that was in the background for ten seconds should not teleport every animation ten seconds forward. - A broken layer turns itself off. Each
updateanddrawruns in atry; a layer that throws is markedbroken, logged once and skipped from then on. One bug in a fish never blanks the whole sunset.
3. Cache what doesn't move#
This is the single biggest performance idea in the project. A layer can be marked still: true. When the stage sorts the layers, it walks the list and merges every run of consecutive still layers into one offscreen canvas, drawn once:
function buildBuckets() {
layers.sort((a, b) => a.z - b.z);
const buckets = [];
let run = null;
for (const L of layers) {
if (L.still) {
if (!run) buckets.push(run = { still: true, layers: [] });
run.layers.push(L);
} else {
run = null;
buckets.push({ still: false, layer: L });
}
}
for (const b of buckets.filter((b) => b.still)) {
b.canvas = new OffscreenCanvas(canvas.width, canvas.height);
const g = b.canvas.getContext('2d');
applyArtboardTransform(g);
for (const L of b.layers) L.draw(g, 0, L);
}
return buckets;
}Each frame, a still bucket costs one drawImage. Cabin walls with hundreds of planks, knots and grain strokes are painted once at load and once per resize. Only the things that actually move (vanes, creatures, smoke, fireflies) are redrawn.
The same idea applies at a smaller scale. The fireflies need a soft glow. A canvas filter: blur() or shadowBlur per insect would be expensive, so the glow is a radial gradient painted once into a 64 × 64 canvas, then stamped with drawImage for every firefly using globalCompositeOperation = 'screen'. Seventy glowing insects cost seventy small blits.
Rule to keep: precompute anything whose look does not depend on time, and make the per-frame work a copy.
4. Hover on the shape, not the box#
Hit-testing uses the real outline of each thing. A layer's hit is a Path2D, often an ellipse or two combined with addPath, and the stage tests it with isPointInPath from the topmost layer down:
const hitCtx = document.createElement('canvas').getContext('2d');
function pick(x, y) { // x, y already in artboard units
for (let i = layers.length - 1; i >= 0; i--) {
const L = layers[i];
if (L.hit && hitCtx.isPointInPath(L.hit, x, y)) return L;
}
return null;
}Three refinements make the interaction feel considered:
- Hit areas are drawn for the motion, not the rest pose. The jumping axolotl's hit ellipse is tall enough to cover it mid-jump, so it doesn't lose hover by leaping out from under the cursor.
- Hover is a number, not a boolean. Each frame every layer eases its
hovertoward 1 or 0:L.hover += (on - L.hover) * (1 - Math.exp(-k * dt)), faster in (k = 5.5) than out (k = 2.4). Draw code multiplies byL.hover, so every reaction fades in and lingers a moment after you leave. That exponential form is frame-rate independent, unlikehover += 0.1. - Touch gets a hold. A tap keeps the hover alive for 2.6 seconds, so a phone user sees the same reaction a mouse user gets by resting.
There is also a debug switch (?hits) that strokes every hit path in cyan and the hovered one in green. Build that switch first; you will need it.
5. Things that feel alive: blink, idle, react#
The creatures are convincing because they never loop. Three tiny state machines do most of the work.
Irregular blinks#
function blinker(rand) {
let wait = 0.6 + rand() * 3, phase = -1;
return {
open: 1,
step(dt) {
if (phase < 0) { if ((wait -= dt) <= 0) phase = 0; return; }
phase += dt / 0.17; // a blink takes 170 ms
this.open = Math.abs(1 - 2 * Math.min(phase, 1));
if (phase >= 1) {
phase = -1; this.open = 1;
wait = rand() < 0.22 ? 0.14 : 1.6 + rand() * 4.2; // one in five: a double blink
}
},
force() { if (phase < 0) wait = 0; }, // blink now, e.g. when hovered
};
}A CSS loop with a fixed period is noticeable after three cycles. A random wait with an occasional double blink never is. force() makes a creature blink the moment the cursor arrives, which reads as "it noticed you".
An idle actor#
Every few seconds each creature picks a small action (a step, a head tilt, a look around, a wiggle) and exposes its progress u from 0 to 1 while it plays:
function actor(rand, actions, gap = [3, 8]) {
let wait = gap[0] + rand() * (gap[1] - gap[0]);
return {
name: null, u: 0, dur: 1, side: 1,
step(dt) {
if (this.name) {
this.u += dt / this.dur;
if (this.u >= 1) { this.name = null; wait = gap[0] + rand() * (gap[1] - gap[0]); }
} else if ((wait -= dt) <= 0) {
[this.name, this.dur] = actions[Math.floor(rand() * actions.length)];
this.u = 0; this.side = rand() < 0.5 ? -1 : 1;
}
},
is(n) { return this.name === n ? this.u : -1; },
};
}
const bump = (u) => (u <= 0 || u >= 1 ? 0 : Math.sin(u * Math.PI)); // 0 → 1 → 0
// in draw(): const tilt = act.is('tilt'); if (tilt >= 0) angle += bump(tilt) * 0.15 * act.side;The draw code composes poses by adding offsets: breathing, plus the wind, plus the current action, plus the hover reaction. Nothing has to know about anything else.
Seeded randomness#
Every creature gets its own seeded generator (a four-line xorshift). Two axolotls never blink in unison, and the scene is identical on every reload, which is essential when you are comparing screenshots while tuning. If you seed with small integers, scramble the seed first (multiply by a large odd constant), or the first few outputs are poorly mixed.
6. Squash, stretch and a jump that never repeats#
Hover the axolotl on the dome roof and it keeps hopping for as long as you stay. The jump is a four-phase state machine:
| Phase | Duration | Pose |
|---|---|---|
| crouch | 0.13 s | squash: wider and lower |
| air | 0.56 s | parabola up and down; stretched at take-off, every third jump a full flip |
| land | 0.22 s | squash on impact, easing out |
| rest | 0.06–0.28 s random | then crouch again while still hovered |
let sq = 0; // > 0 squash, < 0 stretch
if (phase === 'crouch') sq = 0.22 * Math.sin(u * Math.PI / 2);
if (phase === 'air') {
y = -height * 4 * u * (1 - u); // parabola: fast off the ground, hangs at the top
sq = -(0.2 * (1 - u) ** 3 + 0.08 * u ** 3); // stretched leaving, slightly stretched arriving
}
if (phase === 'land') sq = 0.24 * Math.sin(u * Math.PI) * (1 - u * 0.3);
scaleY = 1 - sq;
scaleX = 1 + sq * 0.75; // roughly keep the volumeThree classic animation principles are packed in there: anticipation (the crouch), squash and stretch (with volume roughly preserved), and slow-in / slow-out at the top of the arc, which the parabola gives you for free. A contact shadow under the jumper shrinks and fades as it rises, which sells the height more than the jump itself.
At the top of each jump the axolotl puffs a few hearts. The hearts are a tiny particle system: they pop in with an overshooting outBack ease, then each frame their velocity eases toward a gentle float (vy → -30, vx swaying on a sine), and they fade over the last third of their life. The list is capped at 90 so a determined hoverer cannot grow it without bound.
7. Springs for anything that follows#
When something should follow a moving target (a vane catching up with the wind, a creature's head turning toward you), the project uses a damped spring instead of a tween:
function spring(k = 120, d = 14, x = 0) {
return {
x, v: 0, target: x,
step(dt) {
const a = -k * (this.x - this.target) - d * this.v;
this.v += a * dt;
this.x += this.v * dt;
return this.x;
},
};
}A tween has a fixed duration and restarts awkwardly when the target moves mid-flight. A spring simply keeps chasing: retarget it every frame and it stays smooth, carrying its velocity. k sets the speed (natural frequency √k), d the damping. Critical damping is d = 2√k; below that it overshoots, which is what gives a soft, organic follow.
One caution I learned while porting it: a stiff spring stepped once per frame can gain energy and explode when a frame is long (a throttled background tab, a jank spike). Step it in fixed substeps of a few milliseconds and it stays stable at any frame rate.
8. One wind for the whole picture#
This is my favourite idea in the project. There is one function:
function wind(t, x) {
const u = t * 0.22 + (ART_W - x) * 0.0009; // gusts travel right → left
return 0.8 + 0.45 * noise(u, 3.7)
+ 0.25 * Math.sin(u * 2.3) * Math.max(0, noise(u * 0.5, 9.1))
+ breeze.extra;
}Everything that sways multiplies its motion by wind(t, x) at its own x position: vines, bunting, laundry, lanterns, smoke, drifting leaves, the clouds. Because x is part of the input, a gust visibly travels across the drawing, reaching the right-hand windmill before the left-hand washing line. And hovering the big windmill raises breeze.extra, so the whole town feels the wind pick up.
A shared field turns a collection of individual animations into one world. It costs one noise call per object.
The project also has a tiny event bus (on(name, fn) / emit(name, data)) for the few cases where one part has to tell another something directly, such as the cannon telling the scene it fired.
9. A house style, written down#
The look is consistent across thirty files because the style is a written rule at the top of the engine, not something each file reinvents:
- Flat cel fills: one base tone and one shadow tone, an occasional highlight. No gradients except the sky; no glow, blur or grain.
- One ink colour for every outline, at about 3 units on silhouettes and 1.2–1.8 on inner detail, always with round joins.
- Wear marks: small darker blotches on wood, rust patches on metal.
- One light source, the sunset behind and to the right: a warm rim on right-hand edges and a cool shadow under decks.
Then the shared kit turns those rules into functions. One beam() draws any wooden member with a shadow strip, a warm rim, seeded grain strokes and knots. deck(), rail(), stairs(), ladder() and rope() (with a sag helper and twist ticks) build every structure in the town from the same palette. There are named palettes for wood, treads, railings, metal and rope. When every staircase comes out of the same function, every staircase matches.
A last touch: the whole canvas gets filter: saturate(1.4) in CSS. The browser applies it when compositing, so it is nearly free, and it lets you grade the entire picture with one number.
10. What I moved into my own monkey#
My brand monkey is not a canvas. It is the logo's frozen SVG paths with ink overlays for expressions and CSS for motion. Rebuilding it in Canvas would throw away what already works, so I took the behaviour and kept the rendering. The rule that made this clean: JavaScript computes a few numbers per frame and writes them to CSS custom properties; SVG transforms read them. React never re-renders during the animation.
The new rig.ts is about 250 lines with no imports. It contains four state machines, stepped by one loop in the interactive wrapper:
- Springs for gaze and head. Before, the eyes followed the pointer through a 120 ms CSS transition and the head through a fixed 40 ms delay. Now the eyes are a stiff, nearly critically damped spring (k 900, d 54: 95 % of the way in 0.13 s) and the head a soft, under-damped one (k 90, d 10: 0.23 s and a 13 % overshoot). The head lags the eyes and settles with a little sway, and nobody had to choreograph that.
- Irregular blinks. On the full motion tier, JS times the blinks (random waits, one in five doubled, an instant blink when you hover) and drives
scaleYthrough--mk-bl. On phones the old CSS blink still runs. - An idle actor. When the pointer has been still for two seconds, every four to nine seconds the monkey tilts its head, glances to one side, wiggles or perks up. The actions are added to the spring targets, so they blend with gaze tracking instead of fighting it.
- Hover hops. Rest the cursor on the monkey beside my name on the home page: it turns happy and keeps hopping, with a crouch, a stretch, a parabolic arc, a landing squash, a full flip on every third hop, and a burst of brand-coloured pixels at the top of each.
The two new transforms got their own SVG groups, because the monkey's CSS keeps one transform per element: hop (translate plus scale about the chin line) and spin (rotation about the middle of the face). With the variables unset, both are identity transforms, so every server-rendered, non-interactive monkey on the site is untouched.
One thing I added that the original does not need: the loop sleeps. A full-screen illustration redraws every frame anyway, but a small mascot in a page header should not keep a requestAnimationFrame loop running forever. After each frame the rig checks whether anything is still moving (a spring not yet settled, a blink, an action, a hop, a hover). If nothing is, it stops and sets a timer for whichever comes first, the next blink or the next idle action. Because the state machines work in absolute timestamps rather than accumulated dt, they pick up exactly where they should after the sleep. The rig also stops entirely when the monkey is off-screen, when the tab is hidden, on phones, and under prefers-reduced-motion.
A checklist for the next interactive scene#
- One artboard coordinate space; scale once; cap DPR at 2; fill the window instead of letterboxing.
- Everything is a layer with
z,update,draw,hit. Scene files declare layers and never own the loop. - Clamp
dt. Isolate failures per layer. - Mark static layers
stilland flatten consecutive runs into cached bitmaps. Pre-render glows and sprites once. - Hit-test real shapes with
Path2D, sized for the motion. Ease hover as a number with exponential smoothing. Give touch a hold. - No fixed loops on living things: random blinks, seeded idle actors, offsets that add up.
- Anticipation, squash and stretch with preserved volume, parabolic arcs, contact shadows.
- Springs for anything that follows a moving target; substep stiff ones.
- One shared wind (or light, or time-of-day) field that everything reads.
- Write the style rules down and build a kit of drawing functions that enforce them.
- Build developer switches early: show hit areas, isolate layers, freeze time, render a still, profile per layer.
- Respect the device: pause when hidden or off-screen, and give reduced-motion users a still picture.