vtracer_webapp/
canvas.rs

1use wasm_bindgen::{JsCast};
2use web_sys::{console, 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) -> Canvas {
14        let html_canvas = document().get_element_by_id(canvas_id).unwrap();
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        Canvas {
28            html_canvas,
29            cctx,
30        }
31    }
32
33    pub fn width(&self) -> usize {
34        self.html_canvas.width() as usize
35    }
36
37    pub fn height(&self) -> usize {
38        self.html_canvas.height() as usize
39    }
40
41    pub fn get_image_data(&self, x: u32, y: u32, width: u32, height: u32) -> Vec<u8> {
42        let image = self
43            .cctx
44            .get_image_data(x as f64, y as f64, width as f64, height as f64)
45            .unwrap();
46        image.data().to_vec()
47    }
48
49    pub fn get_image_data_as_color_image(&self, x: u32, y: u32, width: u32, height: u32) -> ColorImage {
50        ColorImage {
51            pixels: self.get_image_data(x, y, width, height),
52            width: width as usize,
53            height: height as usize,
54        }
55    }
56
57    pub fn log(&self, string: &str) {
58        console::log_1(&wasm_bindgen::JsValue::from_str(string));
59    }
60}