Creative Coding From Zero · Episode 01
The Canvas & the Loop
The Canvas & the Loop is Episode 01 of Creative Coding From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
A blank <canvas> and a function that runs sixty times a second is
the entire toolkit. That's it. Everything you've ever seen in generative art — the
flow fields, the particle storms, the dreamy smears of color that look like long-exposure
photographs of something that never existed — is just shapes, drawn in a loop, on a
rectangle of pixels. There is no secret library. There is no special hardware. You
already have all of it built into the browser you're reading this in.
To prove it, the demo below runs the exact same motion through six stages, and somewhere around stage four it stops looking like a coding exercise and starts looking like art. The lever that flips it is a single slider called trail decay. Drag it and watch a sterile bouncing dot turn into a glowing, dreamy streak of light — without changing one line of the motion code. Learn that one trick today and you'll reach for it in every piece you ever make.
Open with stage 6 and just move the trail decay slider from left
to right. At 0 every frame wipes the canvas clean — crisp, sharp, a little
clinical. At 1 nothing is ever erased and the screen smears into a tangled
painting. The sweet spot in the middle is where most generative art lives. The rest of
this episode is just an unpacking of what you're seeing.
What you're looking at
Every stage draws onto the same <canvas> using the 2D context —
the same API whether you're drawing a single rectangle or a swarm of forty shapes. The
canvas is a grid of pixels. Its coordinate system has its origin at the
top-left, x growing to the right and y growing downward
(this trips up everyone who remembers math class — on a canvas, "up" is negative y).
Each frame we call drawing commands, the browser shows the result, and then
requestAnimationFrame calls us again for the next frame.
The one idea worth tattooing on your arm is the difference between the first thing we do each frame. We either clear the canvas — erase everything back to black — or we paint a translucent black rectangle over the whole thing. A full clear gives you a crisp moving shape with no history. A translucent wash only partly erases the previous frame, so old positions fade out slowly instead of vanishing — and that fade is the motion trail. That single choice is the difference between stages 3 and 4, and the slider in stage 6 lets you sit anywhere between them.
Stage 1 — Static primitives
No animation at all. We draw the four things the 2D context can make: a filled
rectangle, a circle (an arc swept a full
turn), a straight line, and a filled path stitched
together from moveTo/lineTo points. Nothing moves, because
nothing is asking it to. This is the vocabulary; everything else in the series is these
same primitives, placed by math and repainted in a loop. Notice the rectangle is
measured from its top-left corner, and the line's endpoints are plain x,y pixels —
that's the coordinate system from the section above, made concrete.
Stage 2 — The loop
Now one circle drifts across the canvas, driven by requestAnimationFrame.
We clear the screen each frame and redraw the circle at its new position. This is the
skeleton of every animation you will ever write: clear, update some numbers,
draw, repeat. Crucially, we move the shape by a delta-time
(dt) — how many seconds passed since the last frame — not by a fixed amount
per frame. That keeps the speed identical on a 60Hz laptop and a 144Hz gaming monitor.
More on why that matters below.
Stage 3 — Clear each frame
Identical to stage 2, called out on its own because it's the baseline you'll compare
everything against. clearRect at the top of the frame wipes the canvas to
transparent black before we draw, so you only ever see the shape's current
position — one crisp circle, no history, razor sharp. This is the correct, sane,
boring default. It is also, for a lot of generative art, exactly the wrong thing.
Stage 4 — Trail (the reveal)
Change one line and the whole feeling changes. Instead of clearRect, we
paint a semi-transparent black rectangle over the entire canvas each
frame: fillStyle = 'rgba(0,0,0,0.08)' then fillRect the whole
thing. Old frames don't disappear — they get darker, a little each frame, until
they finally fade to black. The result is a luminous comet-tail behind the moving shape.
Same motion as stage 3. One different line. Suddenly it looks alive. This is the most
important aesthetic lever in all of generative art, and it costs you nothing.
Stage 5 — Many shapes + trail
Trails get spectacular when there's more than one thing moving. Here a swarm of shapes
rides Lissajous-style paths — x and y each driven by sines at slightly
different frequencies, so each shape traces a looping, weaving curve. With the translucent
wash on, every shape paints a ribbon of light, and the ribbons cross and braid into
something that genuinely looks designed. Push the shapes slider up. It's
still just arc calls in a loop — but it reads as a finished piece.
Stage 6 — Trail-decay live
The payoff. This stage hands you the trail decay slider and blends
smoothly between "clear every frame" and "never erase." At 0 the wash is
fully opaque (a real clear) and you get stage-3 crispness. As you slide toward
1 the wash gets more transparent, trails stretch longer, and near
1 the canvas becomes an ever-accumulating painting that never resets. The
motion underneath never changes — the same swarm on the same paths. Only how
much of the past you keep on screen changes. That's the whole lesson, in one slider.
How the code works
Four pieces of code carry this entire episode. None of them is more than a dozen lines, and you'll reuse all four in every future episode.
1. Canvas, context, and the device-pixel-ratio dance
A canvas has two sizes: its CSS size (how big it looks on the page)
and its backing-store size (how many real pixels it holds). On a retina
screen one CSS pixel is two device pixels, so if you don't account for that, everything
you draw comes out soft and blurry. The fix is to make the backing store
devicePixelRatio times bigger, then scale the context by the
same factor so your drawing code can keep thinking in tidy CSS pixels:
const canvas = document.createElement('canvas');
demo.appendChild(canvas);
const ctx = canvas.getContext('2d');
let W, H, dpr;
function resize() {
dpr = Math.min(window.devicePixelRatio || 1, 2); // cap at 2 — retina is plenty
W = demo.clientWidth;
H = demo.clientHeight;
canvas.width = Math.round(W * dpr); // backing store in real pixels
canvas.height = Math.round(H * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0); // now 1 unit === 1 CSS pixel
}
window.addEventListener('resize', resize);
resize();
After setTransform, every coordinate you pass — W,
H, shape positions — is in clean CSS pixels, and the canvas quietly renders
them at full retina sharpness. Set this up once and forget it forever.
2. The requestAnimationFrame loop, with real delta-time
The loop is a function that does its drawing and then asks the browser to call it
again. The browser calls it right before the next repaint — roughly 60 times a second,
matched to your display. It hands you a timestamp; subtract the last one to get
dt, the seconds elapsed, and multiply all motion by it:
let last = performance.now();
function frame(now) {
const dt = Math.min(0.05, (now - last) / 1000); // seconds; clamp big gaps
last = now;
step(dt); // move everything by dt — never by a fixed amount
draw(); // paint this frame
requestAnimationFrame(frame); // ask for the next one
}
requestAnimationFrame(frame); // kick it off
The Math.min(0.05, …) clamp matters: if the tab is backgrounded and
comes back, now - last could be several seconds, which would teleport every
shape across the canvas. Clamping dt keeps one slow frame from blowing up
the motion.
3. The trail trick: clearRect vs a translucent fillRect
This is the heart of the episode. The first thing draw() does is decide
how much of the previous frame survives. A hard clear keeps nothing; a translucent wash
keeps a fading echo. We blend between them with one number:
function draw() {
if (trail <= 0) {
ctx.clearRect(0, 0, W, H); // crisp: erase everything
} else {
// trail=0 → alpha 1 (full wipe). trail=1 → alpha 0 (never erase).
const alpha = 1 - trail;
ctx.fillStyle = `rgba(10,10,10,${alpha})`; // MUST match the bg color
ctx.fillRect(0, 0, W, H); // dim the past, don't delete it
}
// ... now draw the shapes at their current positions ...
}
The subtle, must-get-right detail: the wash color has to be your
background color. We fade toward rgba(10,10,10,…) because
the page background is #0a0a0a. Fade toward pure black on a dark-grey page
and your trails leave an ugly black halo that never matches. The trail color and the
background are the same color — always.
4. Drawing a shape: paths with moveTo, lineTo, and arc
Every shape is a path you build up and then fill or stroke. beginPath
starts a fresh one, moveTo lifts the pen to a point, lineTo
draws a straight segment, and arc sweeps a circular curve. Here's a circle
and a little triangle, the two shapes the swarm uses:
// a filled circle at (x,y), radius r
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2); // center, radius, start angle, end angle
ctx.fillStyle = color;
ctx.fill();
// a filled triangle, built point by point
ctx.beginPath();
ctx.moveTo(x, y - r); // top (remember: y grows DOWN)
ctx.lineTo(x + r, y + r); // bottom-right
ctx.lineTo(x - r, y + r); // bottom-left
ctx.closePath(); // snap back to the first point
ctx.fillStyle = color;
ctx.fill();
That's the complete drawing API for this episode. arc for round things,
moveTo/lineTo for everything with corners, fill or
stroke to commit it to pixels. The positions come from sines and a seeded
random generator; the look comes from the trail decay layered on top.
Seeded randomness, so a seed reproduces the piece
One last building block you'll see in every episode of this series: we never call
Math.random() directly in the art. Instead each shape's phase and speed come
from mulberry32, a tiny seeded random generator. Same seed → same numbers →
the exact same piece, every reload. The regenerate button just picks a
new seed and rebuilds the swarm:
// Seeded RNG: mulberry32. Same seed → same stream → same artwork.
function mulberry32(seed) {
let a = seed >>> 0;
return function () {
a |= 0; a = (a + 0x6D2B79F5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
let rnd = mulberry32(seed); // rnd() → a number in [0,1)
Common pitfalls
- Clear vs trail confusion (the #1 "why does it look wrong"). If
your animation leaves smears you didn't want, you're painting a translucent rectangle
where you meant to
clearRect. If it won't leave a trail you do want, you're clearing where you meant to wash. Decide on purpose, every frame, which one you're doing. - Everything looks blurry on a retina screen. You sized the canvas
in CSS but forgot the backing store. Set
canvas.width = cssWidth * devicePixelRatioandscale(orsetTransform) the context by the same ratio, as in code block 1. A canvas with no width/height attributes defaults to a fuzzy 300×150 stretched to fit. - Speed differs between machines. If you move shapes by a fixed
number of pixels per frame, your piece runs twice as fast on a 120Hz display.
Always multiply motion by
dt, the elapsed seconds, so it's measured in pixels per second. - Trails leave a colored halo. The translucent wash color must
match the background exactly. We use
rgba(10,10,10,…)to match a#0a0a0apage. Wash with the wrong color and the un-erased residue tints everything over time. - You called
Math.random()in the art path. Then your piece is different every reload and impossible to reproduce or share. Route every random number through the seededmulberry32stream instead.
Exercises
- Additive trails. Before drawing the shapes, set
ctx.globalCompositeOperation = 'lighter'(and reset it to'source-over'before the wash). Now overlapping trails add their light instead of covering each other, and bright crossings bloom white-hot. This is the single most "neon" effect in 2D canvas. Pair it with a long trail decay. - Pulsing speed. Make the swarm's speed breathe by multiplying it by
1 + 0.6 * Math.sin(time * 1.5). The shapes surge and slow in waves, and with trails on you get tight knots where they slow and long streaks where they race — rhythm for free. - Color by index. Right now the shapes are one color. Give shape
ia hue of(i / count) * 360and draw withctx.fillStyle = \`hsl(\${hue} 80% 60%)\`. The swarm becomes a rainbow ribbon. (Next episode we'll see why evenly-spaced hues like this look better than random RGB.)
What's next
Episode 02 — Randomness & Noise. We lean hard on that seeded
generator and ask a question that's secretly the soul of generative art: why does pure
random() look like television static — harsh, jumpy, lifeless — while
noise looks like smoke, terrain, and wind? We'll build value noise from scratch,
watch it turn jitter into something organic, and use it to move these very shapes along
paths that feel hand-drawn instead of mechanical.