Skip to main content

plotting/
canvas.rs

1//! Canvas renderer for the browser. Uses `plotters-canvas::CanvasBackend`
2//! and the shared `draw_on` dispatch in `crate::draw`, so a chart
3//! rendered into a `<canvas>` looks identical to its SVG twin.
4//!
5//! Only compiles under feature `canvas`, which is enabled by the
6//! `nomisync-frontend` WASM crate.
7
8use plotters::prelude::*;
9use plotters_canvas::CanvasBackend;
10use wasm_bindgen::JsValue;
11use web_sys::HtmlCanvasElement;
12
13use crate::draw::{NEUTRAL, draw_on};
14use crate::layout::DEFAULT_TEXT_PX;
15use crate::spec::ChartSpec;
16
17/// Render `spec` into `canvas` via `plotters-canvas`. Sizes the
18/// backing canvas to `device_pixel_ratio` so the chart stays crisp on
19/// `HiDPI` screens; the caller is expected to set the CSS width/height
20/// to the logical size before calling.
21///
22/// # Errors
23///
24/// Returns `Err(JsValue)` when the canvas element cannot be wrapped
25/// (missing 2D context or the shared drawing dispatch fails).
26pub fn render_canvas(spec: &ChartSpec, canvas: &HtmlCanvasElement) -> Result<(), JsValue> {
27    apply_dpr(canvas)?;
28
29    let backend = CanvasBackend::with_canvas_object(canvas.clone())
30        .ok_or_else(|| JsValue::from_str("plotters-canvas: failed to get 2D context"))?;
31    let root = backend.into_drawing_area();
32
33    draw_on(&root, spec, DEFAULT_TEXT_PX, NEUTRAL)
34        .map_err(|e| JsValue::from_str(&format!("draw failed: {e}")))?;
35    root.present()
36        .map_err(|e| JsValue::from_str(&format!("present failed: {e}")))?;
37    Ok(())
38}
39
40/// Multiply the backing store by the window's device pixel ratio so
41/// strokes and text stay crisp. CSS width/height (the logical size)
42/// must be set by the caller — this function only touches the
43/// `width`/`height` attributes on the canvas element.
44fn apply_dpr(canvas: &HtmlCanvasElement) -> Result<(), JsValue> {
45    let dpr = web_sys::window()
46        .ok_or_else(|| JsValue::from_str("no window"))?
47        .device_pixel_ratio();
48    if dpr <= 0.0 || !dpr.is_finite() {
49        return Ok(());
50    }
51
52    let logical_w = f64::from(canvas.client_width().max(1));
53    let logical_h = f64::from(canvas.client_height().max(1));
54    let backing_w = (logical_w * dpr).round().max(1.0) as u32;
55    let backing_h = (logical_h * dpr).round().max(1.0) as u32;
56
57    // Only resize the backing store when the canvas is attached and has
58    // non-zero CSS dimensions. Otherwise leave the author's width/height
59    // attributes untouched.
60    if logical_w > 0.0 && logical_h > 0.0 {
61        canvas.set_width(backing_w);
62        canvas.set_height(backing_h);
63    }
64    Ok(())
65}