- Stack
- JavaScript, Canvas 2D, Web Audio
- In numbers
- 5 landscapes, 4 kinds of weather, 1 number per journey
- Tests
- 11, run on every push
What it is
Sleeper is a night train you watch from outside. A steam train pulls out of a country station and travels through a world that is generated on the fly: cities, forests, fields, coastlines, and mountains, under clear skies, rain, snow, or fog. It stops at stations to let passengers on and off, then passes through tunnels into the next landscape, continuing on a line that never ends.
Everything you see and hear is generated by code using plain JavaScript and the Canvas API. The scene does not load a single image or audio file, uses no frameworks, and has no build step. This means the entire page runs even if you just open the file straight from your hard drive.
The problem
The first version worked, but it looked like a placeholder. Everything was a flat silhouette. There was one dark blue for the train, another for the skyline, and another for the trees. Tunnels were just a fade to black between landscapes, stations existed in the data but were never drawn, and the train never actually stopped.
The deeper problem was that nothing had a real scale. Every layer moved at a speed I had picked by eye, and every carriage was exactly 210 pixels wide regardless of the screen size. Nothing related to anything else, so the scene never felt like a real place.
Before, full size After, full size
The decisions
Measuring the world in metres
The rebuild started with a camera, not with new drawings. The camera is positioned 12 metres from the track and 6 metres up. A single rule converts metres into pixels: anything twice as far away is drawn half as large and moves past the screen half as fast. A telegraph pole is 8 metres tall, and a pine tree is between 15 and 27 metres. They look right next to the train because nothing is sized by hand. The same rule makes each railway sleeper taper towards the far rail, and it turns the wheels by exactly the distance the train has moved, so they no longer slide over the ground.
// Pixels per metre for something z metres away.
function scaleAt(z) {
return camera.focal / z;
}
function groundYAt(z) {
return camera.horizonY + camera.height * scaleAt(z);
}
js/camera.js: every size and every position on screen comes from a distance in metres.One number per journey
A journey is defined by a seed. Instead of using Math.random, which cannot be replayed, the scene uses a small hash function that always returns the same value for the same inputs. The track is divided into slots, and each slot's number decides what sits there. This means the tree in slot 812 is always the same tree. When a journey's landscapes run out, the next stretch is generated using the same number and a counter, so the line never ends and a shared link always unfolds in exactly the same way.
Because a link is just a number, any change to the generator's logic would quietly break every link that had already been shared. To prevent this, a small set of tests runs with Node's built-in test runner on every push. One locks in a specific journey and fails if it changes. Another holds the camera to its rule: twice as far away is drawn half as big and passes half as fast.
Detail drawn once
A station building might have thousands of bricks, a slate roof, a clock, and sash windows. Drawing all of that sixty times a second would be far too slow. To fix this, each building and tunnel face is drawn just once, using its real metre dimensions, onto its own hidden canvas when it is created. Each frame simply places that image at its current distance. The pixel ratio is capped at two, because a ratio of three would mean drawing nine pixels instead of four for every point, for a difference you cannot see. If the frame rate still drops, the canvas resolution scales down automatically.
Tunnels and stations that behave
The front face of a tunnel stands at right angles to the track, so it is drawn in thin vertical strips, with each strip stretched to match the height required by its distance. Originally, the tunnel was drawn over the train in a single layer, which made it look like the train was sliding behind the portal instead of passing through it. I solved this by splitting the tunnel by depth. The far half and the tunnel bore are drawn behind the train, and only the near half is drawn in front.
Stopping at a station comes down to one formula. A train slowing at a steady rate needs v² divided by 2a metres to come to a stop, so braking begins exactly at that distance. Each frame, the formula is reversed to calculate the deceleration needed for the remaining distance. The train always stops exactly on its mark.
Sound without recordings
All sound is generated with the Web Audio API. Filtered noise becomes wind, rain, or steam, while oscillators create the whistle and the squeal of the brakes. The chuffing sound follows the wheels, firing four times for every rotation, and each axle clicks as it passes over the rail joints. The audio follows the engine rather than the screen, so a train inside a tunnel sounds muffled from the outside. A sleep timer gradually fades the sound and darkens the screen, then stops drawing entirely so the computer is not kept busy all night.
What I would do differently
I would start with the camera. Every hand-picked speed in the first version had to be thrown away. If I had established a scale in metres from day one, it would have saved the entire first rewrite.
I would also listen earlier and measure the audio. The first sound mix allowed the rain to drown out everything else, and a later version buried the whistle under the wheels. Measuring each part of the mix individually is what finally fixed it.
Finally, I would watch out for name clashes. The scripts share a single scope so the page can run straight from disk. When two files defined a function with the same name, the later one quietly replaced the earlier one. The forest lost its undergrowth without throwing a single error.
More work on the home page, or the stack behind each project on the CV.