The code in that video is wonderfully small: a canvas, a list of vertices, a list of edges, and a loop. It draws a spinning cube in about eighty lines with no libraries and no matrices. What I wanted to know was how far that formula actually carries. So I fed it real assets — two Porsches, a Mercedes, a Ghibli forest spirit, and a Catbus — and pushed until it broke. It broke twice, in two different and instructive ways.
The One Formula
Put the camera at the origin, looking down the positive z axis, and put a screen at z = 1. A point (x, y, z) in the world casts a ray toward the origin, and that ray crosses the screen somewhere. Where? Similar triangles answer it immediately: the triangle from the origin to the point has depth z and height y; the triangle from the origin to the screen has depth 1 and height y′. The ratios must match.
x′ = xz, y′ = yzThat is the whole of perspective. Not an approximation of it, not a simplified version — that is the thing itself. Objects shrink with distance because you divided by distance. Parallel lines converge because their separation is fixed while z grows without bound, so the quotient tends to zero. The 4×4 matrices, homogeneous coordinates, and clip volumes of a real graphics pipeline are bookkeeping wrapped around this division — they defer it, they let you compose transformations before performing it, and they carry z along for depth testing. But the geometry is one divide.
Getting the Model in Front of the Camera
A model centred on the origin cannot be drawn, because the camera is also at the origin and z = 0 makes the division meaningless. So the model gets pushed away first:
(x, y, z) → (x, y, z + d)This turns out to be the binding constraint on the whole system. If any vertex reaches z ≤ 0 it lands behind the camera and the projection inverts — the model turns inside out and sprays lines across the screen. With d = 1, every vertex must stay strictly inside a unit sphere. Not roughly inside: strictly. And because the model spins about the vertical axis, the quantity that actually matters is not the full bounding sphere but the radius swept in the horizontal plane:
R = max √ x2 + z2A car is long and low. Its bounding sphere is dominated by its length, and normalising by that sphere makes the car look small on screen for no reason — its height, the dimension you actually see side-on, is a fraction of it. Normalising by the swept radius instead sizes the model by the space it will genuinely occupy while turning. Every model here is rescaled so that R = 0.6, which pins the depth range to a known interval, 0.4 ≤ z ≤ 1.6, exactly the fact the transparency scheme later depends on.
Rotation Is Two Lines of Trigonometry
To spin the model about the vertical axis, leave y alone and rotate the (x, z) pair:
x′ = x cos θ − z sin θ, z′ = x sin θ + z cos θIf that looks familiar it is because it is complex multiplication. Write the horizontal position as w = x + iz; then rotating by θ is just w eiθ, and expanding the product gives exactly the two lines above. Rotation in a plane and multiplication by a unit complex number are the same operation, which is also why quaternions — the four-dimensional cousins of complex numbers — are the natural tool for rotation in three dimensions. One of the models in this article, delivered as glTF, stores its orientation exactly that way, as the unit quaternion (0.7071, 0, 0, 0.7071): a quarter turn about x, converting a Z-up model into the Y-up convention the format requires.
From −1…1 to Pixels
The projected coordinates live in a square roughly spanning −1 to 1, and the canvas is measured in pixels with y pointing down. The naive mapping stretches each axis to fill its own dimension:
xpx = x′ + 12 W, ypx = (1 − y′ + 12) HThis is fine while the canvas is square and wrong the instant it is not. On a 16:9 window it applies a horizontal scale of W/2 and a vertical scale of H/2, and a circle in the model becomes an ellipse on screen. The fix is to use one scale for both axes — the largest centred square the canvas can hold — and let the wider dimension simply show more empty background:
s = min(W, H)2, xpx = W2 + x′s, ypx = H2 − y′sThe minus sign on the second line is the entire coordinate-system conversion: mathematics puts y up, screens put it down.
What a Model Actually Is
Stripped of textures, normals, materials, and skinning, a renderable model is two arrays: positions, and indices into those positions. The cube is eight corners and twelve edges. Everything in this article has the same shape, only longer.
How much longer is set by topology rather than by taste. On a closed triangulated surface every triangle has three edges and every edge is shared by exactly two triangles, so the edge count follows from the face count alone:
E = 3F2The Catbus obeys this to the digit: 967,326 triangles and precisely 1,450,989 unique edges. It is an STL intended for 3D printing, so it is a watertight manifold and the identity is exact. The cars do not. The Porsche 964 has 93,656 triangles, which would predict 140,484 edges, but yields 144,553 — the extra four thousand are boundary edges belonging to only one triangle, the signature of a model assembled from dozens of open shells rather than one closed surface. Euler's formula tells the same story from the other side: V − E + F equals 2 for a sphere-like closed surface, and −190 for that Porsche, which is a compact way of saying it is made of many disconnected pieces.
Two small choices follow from this. First, storing unique edges rather than triangles halves the work: drawing triangles as closed loops paints every interior edge twice, once from each adjoining face, for an identical picture. Second, a two-index entry should be drawn as one segment and not as a loop that doubles back on itself — a subtle detail that quietly doubled the cost of every edge-pair in the original code.
Reading Real Assets
Downloaded models arrive in whatever their author exported. Getting five of them into the same vertex-and-edge form meant writing four readers, since the environment had no assimp or FBX SDK available:
- OBJ — plain text, one vertex or face per line. An afternoon's work at most.
- FBX — two entirely different formats sharing a name. The binary flavour is a tree of length-prefixed nodes whose numeric arrays are zlib-compressed, with a header layout that widens from 32-bit to 64-bit offsets at version 7500. The ASCII flavour is a brace-delimited text tree. Both were needed; both appear among these models.
- STL — the simplest possible format: an 80-byte header, a triangle count, and fifty bytes per facet with no vertex sharing whatsoever. The Catbus arrives as 2.9 million loose vertices that weld down to 483,633.
- glTF binary — a JSON document and a binary blob in one file, where meshes reference accessors, accessors reference buffer views, and buffer views may be interleaved so that positions are strided through a larger record.
The recurring trap in all of them is the transform hierarchy. Vertices are stored in each part's local frame, and the placement lives in a separate node tree — translation, rotation, and scale composed down from the root. Skip it and the Porsche's wheels sit at the origin in a neat stack instead of under the car; skip it on the glTF and the Mercedes lies on its side, because the quarter-turn that makes it Y-up is stored on the node rather than baked into the vertices.
The First Failure: One Stroke at a Time
With the meshes loaded, the original renderer simply stopped. The Porsche 964 took roughly 0.75 seconds per frame at full-screen
retina resolution — about 1.3 frames per second. The cause was not arithmetic. It was that each of 144,553 edges was drawn by
its own beginPath() / stroke() pair, and each of those carries a fixed cost that has nothing to do with
how long the line is. Add a fresh object allocated for every vertex at every stage of the pipeline — rotate, translate,
project, map to screen — and a single frame was allocating a quarter of a million short-lived objects for the garbage
collector to sweep up.
Batching every edge into one path and projecting each vertex once instead of once per incident edge bought back most of an order of magnitude. It was not enough, and more importantly it was about to become impossible.
The Second Failure: Transparency Wants Per-Line State
Even at a readable frame rate the picture was useless. A wireframe of a hundred thousand edges compressed into a few hundred pixels of car is not a wireframe; it is a solid green silhouette. The line density exceeds the pixel density, and no line width helps — I took it down to a fifth of a pixel and the shape stayed filled.
The remedy is to make depth control opacity, so that the near shell of the model stops painting over everything behind it. With the depth range pinned by the normalisation step, the interpolation parameter is immediate:
t = z − (d − R)2R, α = (1 − t) αnear + t αfar
And here canvas 2D reaches a wall that is structural rather than merely slow. Opacity is context state, not geometry: it is set
by assigning globalAlpha before a draw call. A different opacity per line therefore demands a draw call per line —
exactly the pattern that had just been eliminated. The two requirements are mutually exclusive in that API.
In a shading language they are not even in tension. Opacity becomes a value computed per vertex and interpolated across the primitive, so the entire model remains a single draw call and the transparency is free. That is the actual reason this renderer is written in WebGL, and it is worth being precise about it: the rewrite was not motivated by frame rate. Frame rate was a side effect.
Drawing a Thick Line Without Line Width
One obstacle remains. gl.lineWidth is specified, implemented, and silently clamped to 1 by essentially every desktop
browser — there is no supported way to ask for a thicker line. Lines must therefore be built out of triangles: each edge
becomes a quad, expanded sideways in the vertex shader. Given the two endpoints already projected into pixel coordinates, the
offset direction is the unit normal of the segment,
The ordering matters. The widening has to happen after the perspective divide, in screen space. Widen before it and the width divides by z along with everything else, so the near end of a line going away from you becomes fat and the far end thin — a stylistic effect, but not a line of constant weight. Doing it afterwards costs one normalisation per vertex and gives exact pixel width at any depth.
The whole model is then one instanced draw call: a four-vertex quad template, instanced once per edge, with each instance supplying its two endpoints. The 964's 144,553 edges reach the GPU as two 1.7 MB attribute buffers uploaded once at startup. Per frame, the CPU updates a single float — the angle.
Conserving Ink
One last piece of arithmetic. A fixed pair of opacity constants tuned on a hundred-thousand-edge car saturates into a solid block again on the Catbus, because the ink deposited on a pixel scales with the number of lines crossing it. Holding the product roughly constant keeps the perceived density stable across a range of model sizes spanning five orders of magnitude:
α ← α · min(1, ErefE)With Eref = 150,000 the cars are left untouched, the Catbus is dimmed by a factor of ten, and the cube and the penguin fall below the threshold and are drawn at full strength. The result reads like an X-ray: you see the near surface, the far surface, and the seats and engine in between, all at once.
What It Costs
Frame cost measured on an Apple Silicon laptop at 2560 × 1440 device pixels, averaged over a few hundred frames with a single GPU synchronisation at the end, so the figure is throughput rather than latency:
| Model | Vertices | Triangles | Edges | ms / frame |
|---|---|---|---|---|
| cube | 8 | — | 12 | 0.046 |
| penger | 324 | 624 | 1,872 | 0.165 |
| totoro | 4,460 | 8,836 | 13,282 | 0.338 |
| 300 SL | 45,360 | 96,160 | 134,690 | 2.905 |
| 964 | 50,707 | 93,656 | 144,553 | 3.549 |
| W201 | 106,455 | 185,752 | 292,110 | 6.227 |
| catbus | 483,633 | 967,326 | 1,450,989 | 24.05 |
Above roughly a hundred thousand edges the cost is almost perfectly linear at about 17 nanoseconds per edge, which is the signature of a workload bounded by geometry throughput rather than by anything clever. Everything up to the W201 clears 60 fps with room to spare. The Catbus, at 24 ms, runs around 42 fps — smooth, not perfect, and unsurprising for one and a half million antialiased translucent quads. Its real cost is elsewhere: as a JavaScript source file it is 54 MB and takes a couple of seconds to parse.
For comparison, the same 964 in the original canvas 2D renderer took about 0.75 s per frame. Roughly two hundred times slower, and still without the transparency that made the picture legible in the first place.
Try Them
Each link opens the renderer in a new tab. They are heavy pages — the Catbus in particular is a 54 MB download — so give the larger ones a moment, and prefer a desktop browser with WebGL.
The satisfying part is that nothing in the final renderer contradicts the first formula. The vertex shader still rotates two coordinates with a sine and a cosine, still adds a constant to z, and still divides x and y by it. Everything added afterwards — the instanced quads, the depth-keyed alpha, the ink budget — exists to cope with quantity, not with geometry. A million lines need no more mathematics than twelve do. They just need somewhere better to run.
Credits
The renderer descends from tsoding/formula
by Alexey Kutepov, MIT licensed; the vendored copy under formula/ keeps that licence. The penguin comes from
Max-Kawula/penger-obj.
The five remaining meshes are third-party assets I downloaded rather than made, and their archives shipped without licence files,
so treat them as belonging to their original authors and trace the provenance yourself before reusing any of them.