moon_engine/
web.rs

1//! Web related utilities and the [`Canvas`] alias to [web_sys::HtmlCanvasElement]
2
3use wasm_bindgen::prelude::*;
4use wasm_bindgen::JsCast;
5
6/// An alias for [`web_sys::HtmlCanvasElement`]
7pub type Canvas = web_sys::HtmlCanvasElement;
8
9#[wasm_bindgen]
10extern "C" {
11    #[wasm_bindgen(js_namespace=console)]
12    pub fn log(s: &str);
13}
14
15/// A macro that can be used to write output to the browser
16#[macro_export]
17macro_rules! console_log {
18    ($($t:tt)*) => (crate::web::log(&format_args!($($t)*).to_string()))
19}
20
21/// Get the time in seconds using [`Performance`](web_sys::Performance)
22///
23/// # Examples
24///
25/// ```no_run
26/// # use moon_engine::web::now_sec;
27/// let time = now_sec();
28/// println!("The current time is: {}", time);
29/// ```
30pub fn now_sec() -> f64 {
31    web_sys::window().unwrap().performance().unwrap().now() / 1000.0
32}
33
34/// Initialize document-level callbacks
35pub fn setup_document_events() -> Result<(), JsValue> {
36    let document = web_sys::window().unwrap().document().unwrap();
37    {
38        let closure = Closure::wrap(Box::new(move |event: web_sys::KeyboardEvent| {
39            if event.is_composing() || event.key_code() == 229 {
40                return;
41            }
42            panic!("Key was pressed {}", event.key());
43        }) as Box<dyn FnMut(_)>);
44        document.add_event_listener_with_callback("keydown", closure.as_ref().unchecked_ref())?;
45        closure.forget();
46    }
47    Ok(())
48}