Canvas-Based Graphics & Animation
local graph
Chapter 8 — Canvas-Based Graphics & Animation
Section titled “Chapter 8 — Canvas-Based Graphics & Animation”Chapter 8 – Canvas-Based Graphics & Animation
Section titled “Chapter 8 – Canvas-Based Graphics & Animation”Drawing directly to an HTML5 <canvas> from Rust unlocks the full power of WebAssembly for games, data visualizations, and interactive art.
8.1: Canvas API Primer in Rust
Section titled “8.1: Canvas API Primer in Rust”Drawing on an HTML5 <canvas> from Rust gives you direct, high-performance control over pixels, shapes, and text. The web-sys crate exposes the browser’s native Canvas APIs, so you can call methods like fill_rect, stroke, and draw_image without a shred of JavaScript. Let’s unpack the essentials.
A. Enabling the Right Features
Section titled “A. Enabling the Right Features”In your Cargo.toml, include only the Web APIs you need:
[dependencies]wasm-bindgen = "0.2"web-sys = { version = "0.3", features = [ "Window", "Document", "HtmlCanvasElement", "CanvasRenderingContext2d", "Path2d"] }- HtmlCanvasElement: the
<canvas>element itself - CanvasRenderingContext2d: 2D drawing methods
- Path2d: reusable complex paths
B. From Canvas Tag to Drawing Context
Section titled “B. From Canvas Tag to Drawing Context”flowchart TDA[HTML: <canvas id="c">] --> B[window().document()]B --> C[get_element_by_id("c")]C —> D[dyn_into::<Htm’C D —> E[get_context(“2d” E —> F[dyn_into::<Ca
Rust Implementation:
use wasm_bindgen::prelude::*; use web_sys::{window, CanvasRenderingContext2D};
#[wasm_bindgen(start)] pub fn setup_canvas() -> Result<(), JsValue> { // 1. Grab window & document let doc = window().unwrap().document();
// 2. Get the <canvas> elementlet canvas = doc .get_element_by_id("c") .ok_or("Canvas not found")? .dyn_into::<HtmlCanvasElement>()?;
// 3. Obtain the 2D contextlet ctx = canvas .get_context("2d")? .ok_or("Context type not available")? .dyn_into::<CanvasRenderingContext2D>()?;
// 4. (Optional) Resize to match CSS sizelet w = canvas.client_width() as u32;let h = canvas.client_height() as u32;canvas.set_width(w);canvas.set_height(h);
// 5. Draw a filled rectanglectx.set_fill_style(&JsValue::from_str("#3498db"));ctx.fill_rect(20.0, 20.0, 150.0, 100.0);
Ok(())}
C. Basic Drawing Operations
Once you have ctx: CanvasRenderingContext2D, you can:
- Fill and Stroke Shapes
// Filled circle
0.0, 0.0, std::f64::consts::PI * #e74c3c”.into());
0); .0); .0); _path stroke e(); 2ecc71”.into());
raw Text
_font(” t_fill_st ll_text( ); 150”.into()); nvas!”, 20.0, 200.0)?;
Use Path2d for Reusable Paths
Section titled “Use Path2d for Reusable Paths”star = web_sys::Path2d::new_with_str( "M100,10 L40,198 L190,78 L10,78 L160,198 Z");ctx.set_fill_style(&"#f1c40f".into());ctx.fill_with_path(&star);D. Case Study: Interactive Drawing App
Section titled “D. Case Study: Interactive Drawing App”I built a simple drawing board where mouse events (covered in the next chapter) feed into Rust functions that call line_to and stroke. By batching these path commands into a Path2d, the UI remained responsive even with thousands of points—far smoother than the equivalent JavaScript version.
E. Personal Insights & Best Practices
Section titled “E. Personal Insights & Best Practices”- Sync size early: Always set
canvas.widthandcanvas.heightto match CSS dimensions—otherwise your drawing may scale unexpectedly.
C —> D[dyn_into::
Rust Implementation:
Section titled “Rust Implementation:”use wasm_bindgen::prelude::*; use web_sys::{window, HtmlCanvasElement, CanvasRenderingContext2d};
#[wasm_bindgen(start)] pub fn setup_canvas() -> Result<(), JsValue> { // 1. Grab window & document let doc = window().unwrap().document().unwrap();
// 2. Get the <canvas> elementlet canvas = doc .get_element_by_id("c") .ok_or("Canvas not found")? .dyn_into::<HtmlCanvasElement>()?;
// 3. Obtain the 2D contextlet ctx = canvas .get_context("2d")? .ok_or("Context type not available")? .dyn_into::<CanvasRenderingContext2d>()?;
// 4. (Optional) Resize to match CSS sizelet w = canvas.client_width() as u32;let h = canvas.client_height() as u32;canvas.set_width(w);canvas.set_height(h);
// 5. Draw a filled rectanglectx.set_fill_style(&JsValue::from_str("#3498db"));ctx.fill_rect(20.0, 20.0, 150.0, 100.0);
Ok(())}
C. Basic Drawing Operations
Section titled “C. Basic Drawing Operations”Once you have ctx: CanvasRenderingContext2d, you can:
1. Fill and Stroke Shapes
Section titled “1. Fill and Stroke Shapes”// Filled circle
ctx.begin_path(); ctx .arc(100.0, 75.0, 50.0, 0.0, std::f64::consts::PI * 2.0)?; ctx.set_fill_style(“#e74c3c”.into()); ctx.fill();
// Stroke a polygon ctx.begin_path(); ctx.move_to(200.0, 50.0); ctx.line_to(250.0, 100.0); ctx.line_to(200.0, 150.0); ctx.close_path(); ctx.set_stroke_style(“#2ecc71”.into()); ctx.stroke();
2. Draw Text
Section titled “2. Draw Text”ctx.set_font(“24px serif”); ctx.set_fill_style(“#2c3e50”.into()); ctx.fill_text(“Hello, Canvas!”, 20.0, 200.0)?;
3. Use Path2d for Reusable Paths
Section titled “3. Use Path2d for Reusable Paths”let star = web_sys::Path2d::new_with_str( “M100,10 L40,198 L190,78 L10,78 L160,198 Z” )?; ctx.set_fill_style(“#f1c40f”.into()); ctx.fill_with_path(&star);
D. Case Study: Interactive Drawing App
Section titled “D. Case Study: Interactive Drawing App”I built a simple drawing board where mouse events (covered in the next chapter) feed into Rust functions that call line_to and stroke. By batching these path commands into a Path2d, the UI remained responsive even with thousands of points—far smoother than the equivalent JavaScript version.
E. Personal Insights & Best Practices
Section titled “E. Personal Insights & Best Practices”- Sync size early: Always set
canvas.widthandcanvas.heightto match CSS dimensions—otherwise your drawing may scale unexpectedly.
- Batch operations: Group calls between
begin_path()andfill()/stroke()to minimize state changes. - Cache expensive paths: Use
Path2dfor static shapes you reuse each frame. - Avoid unnecessary allocations: Reuse context settings (colors, fonts) rather than calling setters every time.
- Acquire the 2D context via
web-syswithdyn_into. - Draw rectangles, circles, polygons, and text using familiar canvas calls—now in Rust.
- Optimize by resizing canvas correctly, batching draws, and reusing
Path2d.
8.2: Rendering Loops & Frame Scheduling
Section titled “8.2: Rendering Loops & Frame Scheduling”Animating at a smooth 60 fps requires you to coordinate Rust logic with the browser’s repaint cycle. In JavaScript, you’d use requestAnimationFrame; in Rust–Wasm, you do the same—but with a bit of ceremony around closures and lifetime management. Let’s unpack everything:
A. The Rendering Loop Pattern
Section titled “A. The Rendering Loop Pattern”-
State Initialization
Create any shared state (positions, velocities, timestamps) in anRc<RefCell<...>>. -
Define the Frame Callback
Wrap a Rust closure inClosure::wrap, accepting af64timestamp. -
Schedule the First Frame
Callwindow().request_animation_frame(callback_ref). -
Inside the Callback
- Compute delta time: dt = (timestamp - last_timestamp) / 1000.0.
- Update your state using dt.
- Draw the new frame via your canvas context.
- Re-schedule the next frame by calling requestAnimationFrame again.
flowchart TD A[Start Animation] —> B[Create Closure] B —> C[requestAnimationFrame(callback)] C —> D[Browser calls callback(timestamp)] D —> E[Compute dt & update state] E —> F[Draw frame] F —> G[requestAnimationFrame(callback)] G —> D
B. Working Example: Bouncing Ball
use wasm_bindgen::prelude::*; use web_sys::{window, HtmlCanvasElement, CanvasRenderingContext2d}; use std::{rc::Rc, cell::RefCell};
#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
// 1. Setup canvas and context
let doc = window().unwrap().document().unwrap();
let canvas = doc.get_element_by_id(“canvas”)
.unwrap().dyn_into::
// 2. Initialize shared state: position, velocity, last timestampstruct State { x: f64, vx: f64, last: f64 }let state = Rc::new(RefCell::new(State { x: 50.0, vx: 100.0, last: 0.0 }));
// 3. Prepare the closure holderlet state_closure = state.clone();let cb_ref = Rc::new(RefCell::new(None));let cb_ref_clone = cb_ref.clone();
// 4. Define the frame callback*cb_ref_clone.borrow_mut() = Some(Closure::wrap(Box::new(move |ts: f64| { // a. Compute delta time in seconds let mut st = state_closure.borrow_mut();let dt = (ts - st.last) / 1000.0; st.last = ts;
// b. Update position, bounce at edges st.x += st.vx * dt; if st.x < 0.0 || st.x > canvas.width() as f64 { st.vx = -st.vx; }
// c. Clear and draw ctx.clear_rect(0.0, 0.0, canvas.width().into(), canvas.height().into()); ctx.begin_path(); ctx.arc(st.x, 75.0, 20.0, 0.0, std::f64::consts::PI
- 2.0).unwrap(); ctx.set_fill_style(“#ff6347”.into()); ctx.fill();
// d. Schedule next frame window().unwrap() .request_animation_frame(cb_ref.borrow().as_ref().unwrap(). as_ref().unchecked_ref()) .unwrap(); }) as Box<dyn FnMut(f64)>);
// 5. Kick off the loop with the initial timestamp = 0 window().unwrap() .request_animation_frame(cb_ref.borrow().as_ref().unwrap(). as_ref().unchecked_ref())?;
// Prevent closure from being dropped cb_ref.borrow().as_ref().unwrap().forget();
Ok(()) }
Explanation of Key Steps:
- Rc<RefCell
> lets multiple invocations share and mutate the state. - Closure::wrap converts a Rust closure into a JS-compatible function.
- forget() ensures the closure lives for the page’s lifetime—otherwise it would be dropped, stopping the loop.
- We compute dt every frame, making movement time-based and independent of frame rate.
Personal Insight:
Section titled “Personal Insight:”I once drove a particle system at a fixed step and saw slow machines skip frames. Switching to time-based updates (dt) guaranteed consistent speed everywhere.
C. Managing the Loop’s Lifetime
Section titled “C. Managing the Loop’s Lifetime”-
Stopping the Animation Store the callback reference and call
cancelAnimationFramewhen needed:let handle = window().request_animation_frame(cb_ref).unwrap();- // Later:
window().cancel_animation_frame(handle).unwrap();
-
Memory Safety Always call
.forget()on closures you intend to persist, and drop/unlink them when shutting down to avoid leaks.
D. Case Study: Smooth Scrolling Visualization
Section titled “D. Case Study: Smooth Scrolling Visualization”In a data dashboard, I animated a real-time line chart tied to requestAnimationFrame. By decoupling rendering from data arrival and using dt, the chart remained smooth even under variable data rates. A simple if (dt > 0.1) dt = 0.1; clamp prevented huge jumps when the tab was backgrounded.
Key Takeaways
Section titled “Key Takeaways”- Use
requestAnimationFramefor browser-synced animations—neversetTimeoutfor smoothness. - Time-based updates (using dt) ensure consistent motion across devices.
- Closures and
forget()manage the loop’s lifetime—be explicit about memory ownership.
- Cancel frames to clean up when your component unmounts or animation ends.
8.3: Optimized Draw Calls and Resource Pools
Section titled “8.3: Optimized Draw Calls and Resource Pools”When animating or redrawing complex scenes each frame, naively issuing fresh draw commands can throttle your frame rate. To maintain a blazing-fast 60 fps, you need to reuse work, batch operations, and pool resources.
A. Reusing Paths with Path2d
Section titled “A. Reusing Paths with Path2d”Why it matters:
Section titled “Why it matters:”Constructing complex vector paths every frame allocates new memory and performs parsing each time.
flowchart LRA[Initialize] --> B[Create Path2d once]B --> C[Each Frame: reuse path in fill/stroke]A --> D[Naive]D --> E[Each Frame: new Path2d parsing]C --> F[Fast draw]E --> G[Slower draw]Rust Example:
Section titled “Rust Example:”use web_sys::{CanvasRenderingContext2d, Path2d};use wasm_bindgen::prelude::*;
pub struct Star { path: Path2d,}
impl Star { // Create the reusable star shape pub fn new() -> Self { let d = "M100,10 L40,198 L190,78 L10,78 L160,198 Z"; let path = Path2d::new_with_str(d).expect("Failed to create Path2d"); Star { path } }}// Draw the star at a position pub fn draw(&self, ctx: &CanvasRenderingContext2d, x: f64, y: f64) { ctx.save(); ctx.translate(x, y).unwrap(); ctx.set_fill_style(“#f1c40f”.into()); ctx.fill_with_path(&self.path); ctx.restore(); }
- Create once in your setup phase.
- Call
.draw(...)each frame without reparsing the path string.
B. Offscreen Canvases for Static Scenes
Section titled “B. Offscreen Canvases for Static Scenes”Why it matters: Rendering a static background (grid, map, complex diagram) each frame wastes CPU and GPU cycles.
flowchart TB A[Initialization] —> B[Create offscreen canvas] B —> C[Draw static scene once] C —> D[In render loop: blit offscreen to main canvas] D —> E[Draw dynamic elements]
Rust Example:
use web_sys::{CanvasRenderingContext2d, HtmlCanvasElement};use wasm_bindgen::prelude::*;
#[wasm_bindgen(start)]pub fn init() -> Result<(), JsValue> { let document = web_sys::window().unwrap().document().unwrap(); let main_canvas = document.get_element_by_id("main") .unwrap().dyn_into::<HtmlCanvasElement>()?; let offscreen = HtmlCanvasElement::new()?; offscreen.set_width(main_canvas.width()); offscreen.set_height(main_canvas.height());
let off_ctx = offscreen .get_context("2d")?.unwrap() .dyn_into::<CanvasRenderingContext2d>()?; // Draw static background (grid) off_ctx.set_stroke_style("#ddd".into()); for i in (0..main_canvas.width()).step_by(50) {off_ctx.begin_path(); off_ctx.move_to(i as f64, 0.0); off_ctx.line_to(i as f64, main_canvas.height() as f64); off_ctx.stroke();
// Store offscreen and off_ctx in shared state… Ok(())
// In your render loop: fn render_frame(ctx: &CanvasRenderingContext2d, offscreen: &HtmlCanvasElement) { ctx.draw_image_with_html_canvas_element(offscreen, 0.0, 0.0).unwrap(); // draw dynamic elements on top… }
- Draw once to offscreen in setup.
- Blit in each animation frame—GPU-accelerated copy.
C. Batching Draw Calls
Grouping multiple primitives into a single path reduces context state changes.
pub fn draw_batch(ctx: &CanvasRenderingContext2d, points: &[f64, f64]) { ctx.begin_path(); for &(x, y) in points { ctx.arc(x, y, 5.0, 0.0, std::f64::consts::PI * 2.0).unwrap(); } ctx.set_fill_style(“#3498db”.into()); ctx.fill(); }
- Single begin_path / fill call vs. per-point fill/stroke.
- Minimizes Web API calls and flushing.
D. Pooling Heavy Resources
Section titled “D. Pooling Heavy Resources”For images or buffers that are expensive to load or decode, maintain a pool for reuse.
use web_sys::{HtmlImageElement};use wasm_bindgen::JsCast;
pub struct ImagePool { pool: Vec<HtmlImageElement>,}
impl ImagePool { pub fn new(urls: &[&str]) -> Vec<HtmlImageElement> { urls.iter().map(|&u| { let img = HtmlImageElement::new().unwrap(); img.set_src(u); img }).collect() }
pub fn draw(&self, ctx: &CanvasRenderingContext2d, id: usize, x: f64, y: f64) { let img = &self.pool[id]; ctx.draw_image_with_html_image_element(img, x, y).unwrap(); }}- Preload images in setup.
- Re-use the same HtmlImageElement each frame.
- Avoids network or decode overhead mid-animation.
Case Study: In a sprite-based game, pooling nine character frames in a Vec and drawing by index prevented janky frame drops—avoiding costly new Image() calls each loop.
Recap & Best Practices
Section titled “Recap & Best Practices”- Path2d reuse prevents constant parsing of vector commands.
- Offscreen canvases move static draws out of the per-frame hot path.
- Batching groups primitives into fewer API calls.
<!-- page: 104 -->
- Resource pools preload and reuse heavy assets like images or buffers.- Personal Tip: Profile your loop in DevTools—watch for long tasks in the Performance tab, then apply these strategies to shave off milliseconds.