An interactive canvas demo: add coloured rectangles, drag them around, and control their render order — all driven by Rust compiled to WebAssembly.
| Tool | Install |
|---|---|
| Rust + Cargo | https://rustup.rs |
| wasm-pack | cargo install wasm-pack |
| A local HTTP server | see options below |
wasm-pack build --target webThis compiles the Rust crate to WebAssembly and writes the JS bindings + .wasm file into pkg/.
You need a local HTTP server (browsers block ES-module imports from file://).
Python (no install needed):
python3 -m http.server 8080Node (via npx):
npx serve .Then open http://localhost:8080 in your browser.
| Key / Action | Effect |
|---|---|
A |
Add a new 100×60 rectangle at the canvas centre (random colour) |
| Click & drag | Move any rectangle; the clicked one becomes the active selection |
1 |
Move active rectangle to the back (z-level 0) |
2 |
Move active rectangle to the middle (z-level 1) |
3 |
Move active rectangle to the front (z-level 2) |
Rectangles are drawn in z-level order so higher levels always render on top. The active rectangle gets a white selection outline.
.
├── Cargo.toml # crate config — cdylib, wasm-bindgen, web-sys
├── src/
│ └── lib.rs # World struct: all state + hit-detection + render
├── index.html # canvas + minimal JS glue (event wiring, rAF loop)
└── pkg/ # generated by wasm-pack (gitignore this)
- All state lives in Rust —
Worldholds the rectangle list, active selection, and drag offset. - JS is a thin shell — it forwards DOM events to Rust methods and calls
world.render(ctx)each animation frame. - Hit detection is done in Rust:
mouse_downfinds the topmost rectangle under the cursor (highest z-level, latest index on ties). - Rendering sorts rectangles by z-level each frame and uses the
web-sysCanvas 2D API directly from Rust.