symcode_webapp/
canvas.rs

1use wasm_bindgen::JsCast;
2use web_sys::{CanvasRenderingContext2d, HtmlCanvasElement};
3use visioncortex::ColorImage;
4
5use super::common::document;
6
7pub struct Canvas {
8    html_canvas: HtmlCanvasElement,
9    cctx: CanvasRenderingContext2d,
10}
11
12impl Canvas {
13    pub fn new_from_id(canvas_id: &str) -> Option<Canvas> {
14        let html_canvas = document().get_element_by_id(canvas_id)?;
15        let html_canvas: HtmlCanvasElement = html_canvas
16            .dyn_into::<HtmlCanvasElement>()
17            .map_err(|_| ())
18            .unwrap();
19
20        let cctx = html_canvas
21            .get_context("2d")
22            .unwrap()
23            .unwrap()
24            .dyn_into::<CanvasRenderingContext2d>()
25            .unwrap();
26
27        Some(
28            Canvas {
29                html_canvas,
30                cctx,
31            }
32        )
33    }
34
35    pub fn get_rendering_context_2d(&self) -> &CanvasRenderingContext2d {
36        &self.cctx
37    }
38
39    pub fn width(&self) -> usize {
40        self.html_canvas.width() as usize
41    }
42
43    pub fn set_width(&self, value: usize) {
44        self.html_canvas.set_width(value as u32);
45    }
46
47    pub fn height(&self) -> usize {
48        self.html_canvas.height() as usize
49    }
50
51    pub fn set_height(&self, value: usize) {
52        self.html_canvas.set_height(value as u32);
53    }
54
55    pub fn get_image_data(&self, x: u32, y: u32, width: u32, height: u32) -> Vec<u8> {
56        let image = self
57            .cctx
58            .get_image_data(x as f64, y as f64, width as f64, height as f64)
59            .unwrap();
60        image.data().to_vec()
61    }
62
63    pub fn get_image_data_as_color_image(&self, x: u32, y: u32, width: u32, height: u32) -> ColorImage {
64        ColorImage {
65            pixels: self.get_image_data(x, y, width, height),
66            width: width as usize,
67            height: height as usize,
68        }
69    }
70}