1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-08-09 00:36:37 +02:00
This commit is contained in:
sakex
2023-07-21 19:12:33 +02:00
parent 39ae389af1
commit 7d411b7237
4 changed files with 51 additions and 0 deletions

1
Cargo.lock generated
View File

@ -2354,6 +2354,7 @@ dependencies = [
"js-sys",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
]
[[package]]

View File

@ -299,6 +299,7 @@
- [WebAssembly basics](webassembly.md)
- [Load a WASM module](webassembly/load-wasm-module.md)
- [Import Method](webassembly/import-method.md)
- [web-sys](webassembly/web-sys.md)
- [Expose a method](webassembly/expose-method.md)
- [Expose user-defined Rust types](webassembly/expose-rust-type.md)
- [Borrow Checker](webassembly/borrow-checker.md)

View File

@ -17,3 +17,13 @@ js-sys = "0.3.51"
# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
# code size when deploying.
console_error_panic_hook = "0.1.7"
[dependencies.web-sys]
version = "0.3.4"
features = [
'Document',
'Element',
'HtmlElement',
'Node',
'Window',
]

View File

@ -0,0 +1,39 @@
# web-sys and js_sys
You don't need to import all Javascript methods manually. [web_sys](https://rustwasm.github.io/wasm-bindgen/web-sys/index.html) amd [js_sys](https://docs.rs/js-sys/latest/js_sys/) import Javascript and DOM methods for us.
```rust
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn add_a_cat() -> Result<(), JsValue> {
let window = web_sys::window().expect("no global `window` exists");
let document = window.document().expect("should have a document on window");
let body = document.body().expect("document should have a body");
let image = document.create_element("img")?;
// We need a random number to prevent the browser from caching the image
let random_number = js_sys::Math::random();
image.set_attribute("src", &format!("https://cataas.com/cat?random={random_number}"))?;
body.append_child(&image)?;
Ok(())
}
```
```javascript
import init, {set_panic_hook, add_a_cat} from '/wasm/project.js';
(async () => {
// Run the init method to initiate the WebAssembly module.
await init();
set_panic_hook();
const button = document.createElement("button");
button.textContent = "Add a cat";
document.body.appendChild(button);
button.addEventListener("click", () => {
add_a_cat();
});
})();
```