Brian’s Theme Reborn

"Brian's Theme", reborn in Javascript

Click here to pop this demo out to a full-window view.
Click inside the demo first so it gets the keyboard. Then: 1–9 change the stripe width (and restart the picture), [ speeds it up, ] slows it down.

The whole thing is about 200 lines of JavaScript. None of it is hard, although there a lot going on at once, and more moving pieces than you might expect, because I wanted to get the details true to the original. So here’s how it works, piece by piece.

How “Brian’s Theme Reborn” Works

Step one: a small canvas, blown up

The page is a <canvas> and nothing else. But the canvas isn’t as big as it looks:

canvas.width = window.innerWidth/3;
canvas.height = window.innerHeight/3;
canvas.style.width = window.innerWidth+'px';
canvas.style.height = window.innerHeight+'px';

The first two lines set how many pixels the canvas actually has: 1/3 the window’s width and 1/3 its height. The second two tell the browser to display it at full window size. So every canvas pixel gets stretched to cover a 3×3block of screen pixels. That’s the chunky, low-res look, emulating that Apple II's (if I recall correctly) 280×192 graphics resolution, and it also means there’s only a 1/9 as many pixels to calculate.

Step two: the lines

Every frame of the picture is built out of straight lines that all start at the same point, a random spot picked each time the picture starts over. Drawing a line from one pixel to another on a grid is a classic problem, and the classic answer is Bresenham’s line algorithm. It walks from the start to the end one pixel at a time, using only integer math, and tracks an “error” value that tells it when to step sideways. This is the heart of drawLine():

while (true) {
    for(let w = 0; w < lineWidth; w++) {
        if(phase === 'horizontal') {
            setPixel(currentX, currentY + w, isWhite);
        } else {
            setPixel(currentX + w, currentY, isWhite);
        }
    }

    if (currentX === x2 && currentY === y2) break;
    const e2 = 2 * err;
    if (e2 > -dy) { err -= dy; currentX += sx; }
    if (e2 < dx) { err += dx; currentY += sy; }
}

Plot a pixel, check whether we’ve arrived, otherwise figure out whether to step in X, Y, or both. Repeat. (If you’ve never met this algorithm, it’s worth an afternoon. It’s one of those things that looks like magic until you work through it with pencil and paper, and then looks like magic anyway, but smaller.)

The little for loop on top makes each line two pixels thick (lineWidth = 2), smearing the extra pixel vertically during the first half of a sweep and horizontally during the second.

Note what the function doesn’t do. It doesn’t draw anything. setPixel() just writes a 1 or a 0 into a flat array:

const buffer = new Uint8Array(canvas.width * canvas.height);

function setPixel(x, y, isWhite) {
    if (x >= 0 && x < canvas.width && y >= 0 && y < canvas.height) {
        buffer[y * canvas.width + x] = isWhite ? 1 : 0;
    }
}

That array is the whole picture as far as the program’s concerned: one byte per pixel, and every byte is either “white” or “black.” A “black line” isn’t a line drawn in black. It’s a line that writes zeros, which erases whatever white was there. Keep that in mind, because it matters in a minute.

Step three: the sweep

Each tick of the animation draws four lines. Here’s the first half of the sequence, with the longer lines in the middle trimmed out:

drawLine(currentPos, 0, true);                              // white ray to the top edge
drawLine(currentPos + stepSize, 0, false);                  // black ray, just next to it
drawLine(canvas.width - currentPos, canvas.height, true);   // white ray to the bottom edge
drawLine(canvas.width - currentPos - stepSize, canvas.height, false);
currentPos += stepSize * 2;

One white ray, then a black ray right beside it, aimed at points on the top edge of the canvas that are stepSize pixels apart. Then the same thing in mirror image along the bottom edge, heading the opposite direction. Then currentPos moves along by two steps, and the next tick draws the next white-black pair.

When currentPos runs off the end of the edge, the code flips phase from 'horizontal' to 'vertical' and does the same dance along the left and right edges. Between the two phases you get two “hands,” like the hands of a clock, each sweeping along one side of the window in turn, drawing a stripe wedge behind it.

And because every ray starts from the same origin, near that origin they’re all piled on top of each other, each one overwriting the last. That’s why the area around the starting point turns into a blob, while out at the edges the stripes are cleanly separated. Remember, a black ray erases white.

The stepSize controls how wide those stripes are. Hit a number key and you set it directly. A bigger step means fewer, fatter wedges, and a faster sweep, since each tick covers more of the edge.

Step four: those weird patterns

The odd repeating patterns this forms have a name: moiré. It’s what you get when two regular patterns overlap at slightly different spacings, and your eye picks up the “beat” between them as bands that weren’t drawn by anybody. It’s the same effect as the wavy bands you see when you photograph a TV screen, or lay two wire window screens over each other and slide one.

There’s no moiré code in this page. Nobody ever tells the computer to draw bands. It falls out of the setup, from a few overlapping patterns:

  • The rays against each other. Every ray fans out from the same point, so neighboring rays are only a hair apart in angle. Close to the origin they’re packed so tightly that black rays erase parts of the white ones next to them, and further out, the gaps open up.
  • The rays against the pixel grid. A diagonal line on a grid of square pixels has to be drawn as a staircase. For a nearly flat ray, those steps are long and regular, and when a bunch of near-identical staircases are stacked next to each other, the steps line up in some places and not in others. That’s aliasing, the staircase effect, and it’s what produces the bands.
  • The grid of four. The purple/green pattern arose on the original Apple II because colors were defined by groups of four black or white pixels, as described in the next session, which is yet another regular pattern laid over the other two.

The original’s moiré was the same kind of accident: the sources above describe the Apple’s limited graphics resolution turning closely spaced radial lines into moiré effects. Here, it's still accidental, although the color banding, which was accidental in the original, had to be intentionally recreated here, as modern monitors don't have the same kind of problems producing black-and-white detail that the Apple II did in the early '80s.

Step five: colors - faking the TV

This is the part I like. So far the picture is purely black and white. But these colors, on the Apple II, were produced by “NTSC artifacts,” and here’s where they come from.

Some background: On old computers like the Apple II, the picture went out to a TV or CRT monitor as an NTSC composite signal, which carries color as a phase offset in a high-frequency wave riding on top of the brightness signal. The computer didn’t really have “color” pixels at all in its high-res mode. It just had on/off pixels, switched at a rate tied to that color wave. If you turned pixels on and off in a pattern that happened to line up with the wave, the TV decoded it as color: a particular alternating pattern showed up as one color, and the same pattern shifted by one pixel showed up as the opposite color, purple and green. These are called artifact colors, and a lot of old games exploited them to get color out of hardware that, strictly speaking, couldn’t do it.

Whatever the real hardware did, the page imitates it with a very simple trick. It walks across each row of the buffer in groups of four pixels and looks at the pattern:

const pattern =
    buffer[offset].toString() +
    buffer[offset + 1].toString() +
    buffer[offset + 2].toString() +
    buffer[offset + 3].toString();

if (pattern === "0101") {
    // purple: 128, 0, 128
} else if (pattern === "1010") {
    // green: 0, 128, 0
} else {
    // plain black or white
}

Four pixels, off-on-off-on? Purple. On-off-on-off? Green. Anything else stays black or white. That’s the entire color system. There’s no “color” anywhere in the buffer, only ones and zeros. The color is an interpretation of the pattern at the very last moment before it hits the screen, which is more or less exactly what the old TV was doing too.

“But wait,” I hear you say. “The stripes are two or more pixels wide at the default setting. How do you get a one-pixel-on, one-pixel-off pattern?” You mostly don’t, from the neat stripes. It happens where the stripes get thin and ragged: out where the white and black rays overlap and cut into each other, and wherever a nearly flat ray’s staircase of pixels lines up with the grid. By the same logic, a step size of 1 draws one-pixel stripes, which are exactly the pattern the check is looking for, so the color show up far more often. At wider step sizes, the color only shows up closer to the center of the pattern, where the lines are close enough together to form the alternatine black/white/black/white (0-1-o-1) patterns.

Also worth noticing: the groups of four always start at multiples of four. Pixels 0–3 are a group, pixels 4–7 are the next, and so on. A pattern that straddles the boundary between two groups doesn’t get colored, and a pattern that’s shifted over by one pixel gets the other color. That’s a feature, not a bug, since it’s the same phase business that made the real thing work.

Step six: performance - getting it on screen without slowing to a crawl

Now we have a buffer of ones and zeros and a rule for turning groups of four of them into colors. We still have to get it onto the actual canvas.

The obvious way is to loop over every pixel and call ctx.fillRect(x, y, 1, 1) with the right color. That’s essentially what an earlier version of this page did, for the rows that had changed. It works. It’s also a LOT of tiny drawing calls, and the browser had to go through its whole drawing machinery for each one.

The version we’re looking at does it differently. It creates an ImageData object once, up front, which is nothing more than a big array of numbers (four per pixel: red, green, blue, alpha) that the canvas knows how to display:

const imageData = ctx.createImageData(canvas.width, canvas.height);
const data = imageData.data;

Every frame, renderBuffer() fills in that array directly, using the pattern rule above, and then hands the whole thing to the canvas in one shot:

ctx.putImageData(imageData, 0, 0);

One call per frame, instead of tens or hundreds of thousands. There are two small helpers along for the ride. The picture buffer itself is a Uint8Array, a flat block of bytes representing the entire visual image. And the canvas is created with getContext('2d', { alpha: false }), which promises the browser the canvas will never be see-through, so it can skip some blending work.

Step seven: speed, keys, and clearing the screen

The animation loop runs on requestAnimationFrame, which usually means about 60 times a second. That’s too fast for this effect to be pleasant, so the page only advances the drawing every few frames:

let speedControl = 3;   // higher = slower
let frameCount = 0;

function draw() {
    frameCount++;
    if (frameCount % speedControl === 0) {
        // ...advance the drawing one tick...
    }
    renderBuffer();
    drawMessage();
    requestAnimationFrame(draw);
}

The % (modulo) means “every third frame” when speedControl is 3. The [ and ] keys lower and raise that number between 1 and 10, and the on-screen message flips it around so “bigger is faster” (11 - speedControl out of 10), because telling people “Speed: 3” when 3 is rather slow would just confuse everyone. At the defaults, a back-of-the-envelope estimate on a 1000×700 window with a 60 Hz display puts one sweep along the top edge at around six seconds. Your results may vary, but it’s unhurried.

When the picture finishes, you resize the window, or you press a number key, the screen gets wiped by clearScreen().

This once again simulates the old Apple II's way of clearing the screen in hi-res mode: the screen memory was interlaced, and if you wrote zeros across screen memory, it would blank out the first of every 8 rows, then the 2nd of every 8, the 3rd of every 8, etc., so the entire screen blanks in discrete bands, like a venetian blind rotating closed, not just one wipe from top to bottom:

for(let y = 0; y < canvas.height; y++) {
    if((y % 8) < clearingThickness) {
        const offset = y * canvas.width;
        buffer.fill(0, offset, offset + canvas.width);
        lastBuffer.fill(0, offset, offset + canvas.width);
    }
}
clearingThickness++;

Once clearingThickness goes past 8, it picks a fresh random origin, resets currentPos to 0, flips back to the horizontal phase, and starts the whole thing over somewhere else.

And the key handler, so you can see how little is in it:

window.addEventListener('keydown', (event) => {
    if (event.key >= '1' && event.key <= '9') {
        event.preventDefault();
        stepSize = parseInt(event.key);
        clearScreen();
        showMessage(`Step ${stepSize}`);
    } else if (event.key === '[' && speedControl > 1) {
        event.preventDefault();
        speedControl--;
        showMessage(`Speed: ${11-speedControl}/10`);
    } else if (event.key === ']' && speedControl < 10) {
        event.preventDefault();
        speedControl++;
        showMessage(`Speed: ${11-speedControl}/10`);
    }
});

(The real file has a redundant parseInt check inside that first branch. I simplified it here. It does the same thing either way.)

Known issues

Right now there's a couple of loose ends that need to be cleaned up:

  • Leftovers. There’s a lastBuffer array that gets allocated and zeroed during clearing but never actually read anywhere. It’s a holdover from the earlier version, which compared the current frame against the last one to figure out which rows had changed. The optimized version stopped doing that and nobody removed the array. Same for an unused idx variable at the top of renderBuffer().
  • Redrawing everything every frame. renderBuffer() rebuilds and re-uploads the whole image on every frame, even the frames where nothing in the buffer changed (which, at the default speed, is two out of three). It would be easy to skip those. It just isn’t skipped.
  • The edge of the picture. Because the color-check loop works in groups of four, if the canvas width isn’t a multiple of four, the last few columns never get filled in. By the code, anyway. In practice they’d just stay black, so you’d be hard-pressed to notice.

Everything above is in one file you can save, open, and poke at if you wish. Just click the link above to pop the demo out into its own window and save it. Then: Change lineWidth. Change the purple to something obnoxious. Change the divide-by-2 on the canvas size to a divide-by-8 and watch it turn into a Game Boy having a stroke.

There's also some URL parameters you can use, left undocumented as an easter egg. You can read the code to see those.

Enjoy!

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply