canvas_display/
utils.rs

1//! Collection of helpers (shorthands) to access and create elements in a browser window.
2
3use wasm_bindgen::JsCast;
4use web_sys::{Document, HtmlCanvasElement, HtmlElement, Window};
5
6/// Gets the browser window.
7pub fn window() -> Result<Window, String> {
8    web_sys::window().ok_or("utils::body: no global `windows` exists.".to_string())
9}
10
11/// Gets the document of the browser window.
12pub fn document() -> Result<Document, String> {
13    window()?
14        .document()
15        .ok_or("utils::body: should have a document on window.".to_string())
16}
17
18/// Gets the body of the browser document.
19pub fn body() -> Result<HtmlElement, String> {
20    document()?
21        .body()
22        .ok_or("utils::body: document should have a body.".to_string())
23}
24
25/// Gets a canvas by the given id or create it if it does not exists.
26pub fn canvas(id: &str) -> Result<HtmlCanvasElement, String> {
27    let canvas = {
28        if let Some(canvas) = document()?.get_element_by_id(id) {
29            Some(canvas)
30        } else {
31            if let Ok(canvas) = document()?.create_element("canvas") {
32                canvas.set_id(id);
33                if let Err(_) = body()?.append_child(&canvas) {
34                    return Err("utils::canvas: Could not add canvas to body.".to_string());
35                }
36                Some(canvas)
37            } else {
38                None
39            }
40        }
41    };
42
43    canvas.map_or(
44        Err("utils::canvas: Could not create canvas.".to_string()),
45        |c| {
46            c.dyn_into::<HtmlCanvasElement>()
47                .map_err(|_| "utils::canvas: Could not convert canvas.".to_string())
48        },
49    )
50}
51
52/// Gets the 2d context of the given canvas.
53pub fn context_2d(canvas: &HtmlCanvasElement) -> Result<web_sys::CanvasRenderingContext2d, String> {
54    canvas
55        .get_context("2d")
56        .map_err(|_| "utils::context_2d: Could not get 2d context of canvas".to_string())?
57        .ok_or("utils::context_2d: Could not get 2d context of canvas".to_string())?
58        .dyn_into::<web_sys::CanvasRenderingContext2d>()
59        .map_err(|_| "CanvasDisplay::new: Could not convert canvas context_2.".to_string())
60}
61
62/// Creates a new canvas width given with and height.
63pub fn create_canvas(width: u32, height: u32) -> Result<HtmlCanvasElement, String> {
64    let canvas = document()?
65        .create_element("canvas")
66        .map_err(|_| "utils::create_canvas: Could not create canvas.".to_string())?
67        .dyn_into::<HtmlCanvasElement>()
68        .map_err(|_| "utils::create_canvas: Could not convert canvas.".to_string())?;
69
70        canvas.set_width(width);
71        canvas.set_height(height);
72        
73    Ok(canvas)
74}