TRAVIS J. MACDONALD / THE LAB

Matrix Cube

Where unfinished ideas go instead of dying on a hard drive.

← Back to The Lab

Drag to rotate

BEHIND THE PIXELS

How the Matrix cube works

A small cube, a texture full of letters, and a little maths on the GPU. Here is the journey from an empty canvas to the interactive effect above.

WebGL 112 trianglesOne glyph atlasNo framework
Explore the full source with line-by-line explanations

Hover over a line to see what it does. On a keyboard, Tab into the source and use ↑ / ↓ to move between lines; Escape hides the explanation. On touch, tap a line. The editable playground is below.

Loading source…
View, edit & run the complete source

Edit the same JavaScript that powers the cube above. Start with settings.rain or settings.rotation, then select Run. Your experiment opens in an isolated preview below; it does not change the original cube or save changes to the site.

Loading original source…

01

Give the browser a drawing surface

The HTML canvas is the rectangle on the page. WebGL gives JavaScript access to the GPU through that canvas. This demo uses WebGL 1 directly, with no graphics framework. Its temporary Canvas 2D surface creates the letters; the visible cube is rendered with WebGL.

Try it: drag the cube above. You are moving a real 3D model, not swapping between pictures.

ACTUAL SOURCE · JavaScript · lines 102–114
  var gl = canvas.getContext("webgl", {
    alpha: false,
    antialias: true,
    depth: true,
    stencil: false
  }) || canvas.getContext("experimental-webgl");

  if (!gl) {
    showError("WebGL isn't available in this browser.");
    return;
  }

  // --- glyph atlas -------------------------------------------------------
02

Draw the letters once, reuse them everywhere

An atlas is one texture containing many small character images. Here, letters are drawn in white on black using a hidden 2D canvas. The atlas is uploaded as a GPU texture; the fragment shader samples the letter shapes and colours them green. This avoids creating a DOM element or a separate image file for every character.

Notice the texture filtering and clamp-to-edge settings: these control how the atlas is sampled near its edges.

ACTUAL SOURCE · JavaScript · lines 160–183
  var atlas = document.createElement("canvas");
  atlas.width = ATLAS_COLS * CELL;
  atlas.height = ATLAS_ROWS * CELL;
  var actx = atlas.getContext("2d");
  actx.fillStyle = "#000";
  actx.fillRect(0, 0, atlas.width, atlas.height);
  actx.fillStyle = "#fff";
  actx.font = (CELL - 12) + "px " + picked.font;
  actx.textAlign = "center";
  actx.textBaseline = "middle";
  for (var g = 0; g < GLYPHS.length; g++) {
    var gx = (g % ATLAS_COLS) * CELL + CELL / 2;
    var gy = Math.floor(g / ATLAS_COLS) * CELL + CELL / 2 + 1;
    actx.fillText(GLYPHS[g], gx, gy);
  }

  var tex = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, tex);
  // Canvas rows start at the top; flip them during upload to match the texture-coordinate convention.
  gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, atlas);
  // Clamp at texture edges and use linear sampling to avoid wrapping or jagged magnified letters.
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
03

Build six faces from twelve triangles

GPUs draw triangles. Each cube face becomes two triangles, giving 12 triangles and 36 submitted vertices. Every vertex stores a position, UV coordinates, a face normal and a face ID. UV coordinates describe where a point sits on a face; the face ID lets each side have a different rain pattern.

The cube uses coordinates from −1 to +1. Texture coordinates run from 0 to 1 across each face.

ACTUAL SOURCE · JavaScript · lines 210–215
  const corners = ["bl", "br", "tr", "tl"];
  const uvCorners = [[0, 1], [1, 1], [1, 0], [0, 0]];
  const triangleOrder = [0, 1, 2, 0, 2, 3];
  faces.forEach(f => {
    for (const corner of triangleOrder) pushVert(f[corners[corner]], uvCorners[corner], f.n, f.id);
  });
04

Put the cube in front of a camera

The vertex shader transforms each corner into its final screen position. The model matrix rotates the cube, the view matrix positions the camera relative to it, and projection creates perspective. Matrix multiplication order matters: the rightmost transformation acts first.

MVP means model–view–projection. Perspective makes distant parts appear smaller; the camera distance is fitted to the available drawing area.

ACTUAL SOURCE · JavaScript · lines 621–622
    var view = translate(0, 0, -camDist);
    var mvp = mul(proj, mul(view, model));
05

Animate rain inside a shader

The fragment shader runs for the pixels being drawn. It identifies a column on the face, derives a repeatable pseudo-random speed and trail length, then uses elapsed time to scroll the pattern. The fract function keeps the result between 0 and 1, making each stream wrap around. The atlas supplies the character shapes.

The rain is animated mathematically. There is no video and no JavaScript object moving each individual letter down the cube.

ACTUAL SOURCE · JavaScript · lines 287–301
  float seed = hash(col * 7.13 + vFace * 19.17 + 3.7);
  float speed = mix(0.18, 0.62, hash(seed + 1.3));
  float trailLen = mix(0.28, 0.86, hash(seed + 2.9));
  float shift = uTime * uSpeed * speed + hash(seed + 5.1);
  // fract wraps into [0,1): letters scroll down and re-enter at the top.
  // behind measures distance from the bright leading edge back along its fading trail.
  float yCoord = fract(vUV.y - shift);
  float behind = fract(shift - vUV.y);
  float row = floor(yCoord * rows);
  float yIn = fract(yCoord * rows);
  // Make a brighter head cell and update its glyph faster than the rest of the trail.
  float cellSpan = 1.0 / rows;
  float headCell = 1.0 - smoothstep(cellSpan * 0.15, cellSpan * 1.25, behind);
  float rate = mix(1.6, 5.5, hash(seed + row * 0.37));
  rate = mix(rate, 14.0, step(0.55, headCell));
06

Turn a drag into rotation

Pointer events work with mouse, pen and touch. Pointer capture keeps the gesture attached to the canvas when the pointer leaves its bounds. Movement is converted from pixels to rotation angles using DRAG. The rotation is composed with the current model so dragging remains useful after the cube has already turned.

On release, the recorded angular velocity continues the movement. Exponential decay gradually slows the spin instead of stopping it abruptly.

ACTUAL SOURCE · JavaScript · lines 524–541
  function applyDrag(dx, dy) {
    model = mul(mul(rotY(dx), rotX(dy)), model);
    if (animationPaused && rendererReady && running) frame(performance.now());
  }

  // Only the primary button may start a drag. Capture the pointer so leaving the canvas is harmless.
  listen(canvas, "pointerdown", function (e) {
    if (e.button !== 0 || dragging) return;
    dragging = true;
    pointerId = e.pointerId;
    lastX = e.clientX;
    lastY = e.clientY;
    lastMove = performance.now();
    velYaw = 0;
    velPitch = 0;
    canvas.classList.add("dragging");
    canvas.setPointerCapture(e.pointerId);
  });
07

Render the next frame

requestAnimationFrame schedules work with the browser’s rendering cycle. Each frame calculates elapsed time, advances the animation, uploads the matrices and time to shader uniforms, clears the buffers, and draws the cube. The depth buffer keeps nearer surfaces in front of farther ones.

The 50 ms time-step cap limits jumps after a delayed frame. Canvas sizing also caps device pixel ratio at 2 to limit GPU work on very dense screens.

ACTUAL SOURCE · JavaScript · lines 502–507
    gl.viewport(0, 0, canvas.width, canvas.height);
    var aspect = canvas.width / Math.max(1, canvas.height);
    camDist = fitDistance(aspect);
    proj = perspective(FOV, aspect, 0.08, 50);
    if (animationPaused && rendererReady && running) frame(performance.now());
  }