Matrix rain

Build the falling green code from scratch, and learn the four tricks behind every effect like it.

Green characters falling down a black screen. You've seen it a thousand times, and it still looks like the computer is thinking.

It's an old play of mine, and every time I open it I'm surprised how little is in there. No particles, no physics, no shaders. A grid, one number per column, and a trick with a half-transparent rectangle.

Let's build it, one idea at a time. By the end you'll have the effect, and more usefully, the four ideas that make it work. They show up in half the generative stuff you'll ever write.


Start dumb: one letter per column

Think of the screen as a grid of cells, one character wide and one character tall. Each column has exactly one thing going on in it: a drop, sitting on some row. So the whole state of the effect is one number per column.

rain.js · js file
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
canvas.width = innerWidth
canvas.height = 300

const size = 16                       // one glyph = one cell
const columns = Math.floor(canvas.width / size)
const drops = Array(columns).fill(0)  // the row each column's drop is on

function frame() {
  ctx.fillStyle = 'black'
  ctx.fillRect(0, 0, canvas.width, canvas.height)
  ctx.fillStyle = '#0f0'
  ctx.font = `${size}px 'M PLUS 1 Code', monospace`
  ctx.textBaseline = 'top'
  for (let i = 0; i < columns; i++) {
    ctx.fillText('A', i * size, drops[i] * size)
    drops[i]++
    if (drops[i] * size > canvas.height) drops[i] = 0
  }
  requestAnimationFrame(frame)
}
frame()

A line of A's racing down the screen. Very fast and very boring, but every piece is already here. We just need to fix "fast" and "boring".


Idea 1: the rain moves in cells, not pixels

Right now it steps once per screen refresh, sixty times a second, a whole cell each time. Smooth motion would be the wrong fix: this effect is supposed to tick, like a terminal printing. So we keep the jumps and slow down the clock.

rain.js · js file
~
function frame(now) {
  requestAnimationFrame(frame)
  if (now - last < 50) return   // 20 steps a second, whatever the screen's refresh rate
  last = now
  ctx.fillStyle = 'black'
  ctx.fillRect(0, 0, canvas.width, canvas.height)
  ctx.fillStyle = '#0f0'
  ctx.font = `${size}px 'M PLUS 1 Code', monospace`
  ctx.textBaseline = 'top'
  for (let i = 0; i < columns; i++) {
    ctx.fillText('A', i * size, drops[i] * size)
    drops[i]++
    if (drops[i] * size > canvas.height) drops[i] = 0
  }
}
...
- frame()
+ let last = 0
+ requestAnimationFrame(frame)

requestAnimationFrame still calls us at 60 or 120 or 144Hz, depending on the screen. We just skip the calls that come too soon. That's a fixed-step clock, and it's what keeps the effect the same speed on every machine. (A 120Hz laptop would otherwise rain twice as fast as a 60Hz monitor.)


Idea 2: don't erase, fade

Here's the trick that makes the whole effect. Instead of clearing the canvas every step, paint a mostly transparent black rectangle over it:

rain.js · js file
- ctx.fillStyle = 'black'
+ ctx.fillStyle = 'rgb(0 0 0 / 0.08)'   // dim last step's glyphs a little, don't erase them

Every character you've ever drawn is still on the canvas. Each step dims it by 8%, so a glyph drawn ten steps ago is at about 43% brightness, and thirty steps ago it's at about 8%. The tail isn't something we draw. It's what's left of the old glyphs.

The alpha is the tail's length. Try a heavier hand:

js · run rain.js
- ctx.fillStyle = 'rgb(0 0 0 / 0.08)'
+ ctx.fillStyle = 'rgb(0 0 0 / 0.3)'

Short and punchy. And a very light one:

js · run rain.js
- ctx.fillStyle = 'rgb(0 0 0 / 0.08)'
+ ctx.fillStyle = 'rgb(0 0 0 / 0.02)'

Long smears, and if you look closely, the old trails never quite reach black. Remember that, we'll come back to it.

This is the oldest trick in canvas animation: the canvas is a memory, and a translucent fill is how you make it forget slowly. Motion trails, light painting, comet tails and smoky cursors are all this one line.


Idea 3: randomness goes in the reset

Our columns still march in lockstep, a single line sweeping down. The fix is not to give every column a random speed. It's one coin toss, at the moment a drop leaves the screen:

rain.js · js file
- if (drops[i] * size > canvas.height) drops[i] = 0
+ if (drops[i] * size > canvas.height && Math.random() > 0.975) drops[i] = 0

A drop that falls off the bottom keeps falling, invisibly, until it wins a 1-in-40 toss. Every column waits a different random time below the screen, so they drift apart all by themselves after the first pass.

The first pass is still a wall, though, because every drop starts on row zero. So let's scatter the starts above the screen too:

rain.js · js file
- const drops = Array(columns).fill(0)
+ const drops = Array.from({length: columns}, () => -Math.floor(Math.random() * 40))

A negative row is just "somewhere above the top edge". Nothing special needed, fillText above the canvas draws nothing.

The principle is bigger than rain: put randomness where a cycle restarts, not inside every step. Random per step gives you jitter. Random per restart gives you independent lives, and that reads as natural.


Characters, finally

The film used half-width katakana (mirrored, actually) plus digits. Pick a fresh one every step. The demos load M PLUS 1 Code from Google Fonts for them: a monospace face that actually has katakana, so every glyph sits in its cell. (A canvas never asks for a web font by itself, so the page calls document.fonts.load() once, naming every glyph: Google serves a font like this in dozens of small pieces, and only fetches the pieces for the characters you name.)

rain.js · js file
+ const glyphs = 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン0123456789'
const size = 16
...
- ctx.fillText('A', i * size, drops[i] * size)
+ const glyph = glyphs[Math.floor(Math.random() * glyphs.length)]
+ ctx.fillText(glyph, i * size, drops[i] * size)

Because only the head gets a new glyph and the tail is just faded old glyphs, the column looks like it's changing while it falls. That's free, we didn't write any of it.


Idea 4: the head is a second pass

In the film, the leading character glows almost white and the tail is green. One fillStyle can't do that, so we keep one more number per column: the glyph the head showed last step. Each step that cell gets repainted green, and the new head goes in bright:

rain.js · js file
const drops = Array.from({length: columns}, () => -Math.floor(Math.random() * 40))
+ const heads = Array(columns).fill('')   // the glyph each head showed last step
...
- ctx.fillStyle = '#0f0'
ctx.font = `${size}px 'M PLUS 1 Code', monospace`
...
const glyph = glyphs[Math.floor(Math.random() * glyphs.length)]
- ctx.fillText(glyph, i * size, drops[i] * size)
+ ctx.fillStyle = '#0f0'
+ ctx.fillText(heads[i], i * size, (drops[i] - 1) * size)   // last step's head joins the tail
+ ctx.fillStyle = '#dfd'
+ ctx.fillText(glyph, i * size, drops[i] * size)
+ heads[i] = glyph

Drawing the same glyph twice in the same spot works because the second paint covers the first exactly. The canvas has no layers, so "change the color of what's already there" means "draw it again on top". Keep that in mind any time you want something to become something else.

That's the effect. Everything from here is the less-basic stuff: what separates "it works" from "it looks good".


Depth: the same rain, three times

Real depth needs a camera and a z-buffer. Fake depth needs three copies of what we already have, each one tuned like it's a different distance away:

  • far: small glyphs, slow steps, dim colors
  • near: big glyphs, fast steps, bright colors

Small and slow and dim is the trick. Any one of those alone reads as "different", all three together read as "farther". That's parallax plus atmosphere, the same two cues landscape painters have used forever.

So the rain becomes a function, one per layer, each with its own clock:

layers.js · js file
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
const W = innerWidth, H = 300
const dpr = devicePixelRatio || 1
canvas.width = W * dpr                // the backing store at the screen's real resolution…
canvas.height = H * dpr
canvas.style.width = W + 'px'         // …shown at CSS size, so glyphs stay sharp on retina
ctx.scale(dpr, dpr)
ctx.textBaseline = 'top'

const glyphs = 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン0123456789'
const pick = () => glyphs[Math.floor(Math.random() * glyphs.length)]

function rain(size, stepMs, tail, head) {
  const columns = Math.floor(W / size)
  const drops = Array.from({length: columns}, () => -Math.floor(Math.random() * 40))
  const heads = Array(columns).fill('')
  let last = 0
  return now => {
    if (now - last < stepMs) return
    last = now
    ctx.font = `${size}px 'M PLUS 1 Code', monospace`
    for (let i = 0; i < columns; i++) {
      const x = i * size, y = drops[i] * size
      ctx.fillStyle = tail
      ctx.fillText(heads[i], x, y - size)
      heads[i] = pick()
      ctx.fillStyle = head
      ctx.fillText(heads[i], x, y)
      drops[i]++
      if (y > H && Math.random() > 0.975) drops[i] = 0
    }
  }
}

const layers = [
  rain(10, 90, 'rgb(0 110 30)', 'rgb(110 170 120)'),   // far: small, slow, dim
  rain(16, 60, 'rgb(0 190 40)', 'rgb(190 245 190)'),
  rain(26, 40, 'rgb(0 255 70)', 'rgb(235 255 235)'),   // near: big, fast, bright
]

ctx.fillStyle = 'black'
ctx.fillRect(0, 0, W, H)

function frame(now) {
  requestAnimationFrame(frame)
  ctx.fillStyle = 'rgb(0 0 0 / 0.06)'
  ctx.fillRect(0, 0, W, H)
  for (const step of layers) step(now)
}
requestAnimationFrame(frame)

A few things changed shape here, and each is a small principle of its own:

  • One fade, every layer. The fade now runs on every screen frame, not on a layer's step, because the layers tick at different speeds and the fade belongs to none of them. It runs more often now, so its alpha went down.
  • Each layer owns its clock. rain() returns a function with last closed inside it. The frame loop doesn't know or care how fast a layer ticks.
  • Sharp text on retina. The canvas used to be innerWidth pixels wide, and on a 2x screen the browser stretched it, so every glyph was blurry. Now the backing store is W * dpr real pixels, shown at W CSS pixels, and ctx.scale(dpr, dpr) lets us keep thinking in CSS pixels.
  • Paint the first frame. A fresh canvas is transparent, and a 6% fade takes a couple of seconds to build up to black. One opaque fill at the start skips that.

The ghost problem

Remember the 2% fade, where the old trails never quite went away? That's not your eyes, it's arithmetic.

A canvas stores each color channel as a whole number from 0 to 255. Painting black at 6% means new = round(old × 0.94). Follow a dim green pixel down:

  • 100 → 94 → 88 → … → 17 → 16 → 15 → … → 9 → 8 → 8 → 8

At 8, 8 × 0.94 = 7.52, which rounds back to 8. The pixel is stuck forever. Every channel below roughly 0.5 / alpha can never fade: below 8 at 6%, below 25 at 2%. That's why light fades leave a grey-green haze over everything.

Three ways out, from cheapest to most correct:

  1. Use a fade that's strong enough that the stuck level is too dark to see. That's why 6–8% is the sweet spot for this effect.
  2. Every so often, paint full black over very dark pixels. For example, every 100 frames draw black with globalCompositeOperation = 'darken'.
  3. Stop fading pixels altogether: remember each cell's age and draw it at a computed brightness. More code, but no ghosts, and you can color the tail any way you like.

For matrix rain, option 1 is the honest answer. But the day you build a long-exposure effect and wonder why the black never comes back, now you know.


What to take away

The basic ideas, the ones that got us to "it works":

  • State is the smallest thing that describes the picture. Here it's one number per column, not one object per character.
  • A fixed-step clock separates "how often the screen refreshes" from "how often the world moves".
  • A translucent fill instead of a clear turns the canvas into a memory that forgets slowly. Trails come for free.
  • Randomness at the restart, not at every step, gives each column its own life.

And the less basic ones, the ones that made it look good:

  • Draw twice to change something. The canvas has no objects, only pixels, so "the head turns green" means painting over it.
  • Depth is a bundle of cues: smaller, slower and dimmer together. Not one of them alone.
  • Render at the device's pixel ratio, or text is the first thing that looks cheap.
  • 8-bit fades have a floor. Know where it is before you choose an alpha.

None of these are about letters. Swap fillText for a dot and it's snow. Swap the direction and it's sparks. Keep the fade and drop the grid, and you're painting with light. The rain was just a good excuse.

Comments & reactions

Sign in with GitHub to join the conversation.

Comments load as you reach this section.