[WASM Rust] Use the js-sys Crate to Invoke Global APIs Available in Any JavaScript Environment

js-sys offers bindings to all the global APIs available in every JavaScript environment as defined by the ECMAScript standard.

In this lesson, we will install and use js-sys to invoke JavaScript's Date API to grab the current time. The date will need to be converted to a value Rust can use and display that date from Rust in the browser.

Cargo.toml:

[dependencies]
cfg-if = "0.1.5"
wasm-bindgen = "0.2.25"
js-sys = "0.2"

lib.rs:

// Called by our JS entry point to run the example
#[wasm_bindgen]
pub fn run() {
    let now = js_sys::Date::now();
    let now_date = js_sys::Date::new(&JsValue::from_f64(now));
    
    let val = document.createElement("p");

    val.set_inner_html(&format!(
        "Hello from Rust, it's {}:{}",
        now_date.get_hours(),
        now_date.get_minutes()
    ));
    document.body().append_child(val);
}

index.js:

import("../crate/pkg").then(module => {
    module.run();
  });

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/9920062.html