1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//! Collection of helpers (shorthands) to access and create elements in a browser window.

use wasm_bindgen::JsCast;
use web_sys::{Document, HtmlCanvasElement, HtmlElement, Window};

/// Gets the browser window.
pub fn window() -> Result<Window, String> {
    web_sys::window().ok_or("utils::body: no global `windows` exists.".to_string())
}

/// Gets the document of the browser window.
pub fn document() -> Result<Document, String> {
    window()?
        .document()
        .ok_or("utils::body: should have a document on window.".to_string())
}

/// Gets the body of the browser document.
pub fn body() -> Result<HtmlElement, String> {
    document()?
        .body()
        .ok_or("utils::body: document should have a body.".to_string())
}

/// Gets a canvas by the given id or create it if it does not exists.
pub fn canvas(id: &str) -> Result<HtmlCanvasElement, String> {
    let canvas = {
        if let Some(canvas) = document()?.get_element_by_id(id) {
            Some(canvas)
        } else {
            if let Ok(canvas) = document()?.create_element("canvas") {
                canvas.set_id(id);
                if let Err(_) = body()?.append_child(&canvas) {
                    return Err("utils::canvas: Could not add canvas to body.".to_string());
                }
                Some(canvas)
            } else {
                None
            }
        }
    };

    canvas.map_or(
        Err("utils::canvas: Could not create canvas.".to_string()),
        |c| {
            c.dyn_into::<HtmlCanvasElement>()
                .map_err(|_| "utils::canvas: Could not convert canvas.".to_string())
        },
    )
}

/// Gets the 2d context of the given canvas.
pub fn context_2d(canvas: &HtmlCanvasElement) -> Result<web_sys::CanvasRenderingContext2d, String> {
    canvas
        .get_context("2d")
        .map_err(|_| "utils::context_2d: Could not get 2d context of canvas".to_string())?
        .ok_or("utils::context_2d: Could not get 2d context of canvas".to_string())?
        .dyn_into::<web_sys::CanvasRenderingContext2d>()
        .map_err(|_| "CanvasDisplay::new: Could not convert canvas context_2.".to_string())
}

/// Creates a new canvas width given with and height.
pub fn create_canvas(width: u32, height: u32) -> Result<HtmlCanvasElement, String> {
    let canvas = document()?
        .create_element("canvas")
        .map_err(|_| "utils::create_canvas: Could not create canvas.".to_string())?
        .dyn_into::<HtmlCanvasElement>()
        .map_err(|_| "utils::create_canvas: Could not convert canvas.".to_string())?;

        canvas.set_width(width);
        canvas.set_height(height);
        
    Ok(canvas)
}