Snake on canvas
The classic, in Canvas 2D and TypeScript with no libraries. A custom element, a fixed-timestep game loop and game logic kept apart from drawing.
Score 0
Best 0
Arrow keys or WASD to move, Space or P to pause. On touch: swipe on the board or use the buttons.
How it works
- The logic (logic.ts) is pure: state and functions, no DOM. It can be tested on its own.
- The game loop uses requestAnimationFrame with a fixed-timestep accumulator: speed does not depend on the screen refresh rate.
- Turns go into a small queue, so two quick key presses within one tick are not lost.
- Colours come from the site’s CSS tokens and follow the light/dark theme.
- The game pauses when the board loses focus or the tab is hidden.
Source code: src/pages/lab/snake