1use wasm_bindgen::JsCast;
4use web_sys::{Document, HtmlCanvasElement, HtmlElement, Window};
5
6pub fn window() -> Result<Window, String> {
8 web_sys::window().ok_or("utils::body: no global `windows` exists.".to_string())
9}
10
11pub fn document() -> Result<Document, String> {
13 window()?
14 .document()
15 .ok_or("utils::body: should have a document on window.".to_string())
16}
17
18pub fn body() -> Result<HtmlElement, String> {
20 document()?
21 .body()
22 .ok_or("utils::body: document should have a body.".to_string())
23}
24
25pub 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
52pub 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
62pub 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}