This projects contains my experiments for learning WebAssembly with Rust.
- in progress
- finished
- no longer continued
- Rust (rustup -> rustc, cargo)
- wasm-pack (https://rustwasm.github.io/wasm-pack/installer/)
- optional: cargo generate for ('cargo install cargo-generate' for 'cargo generate --git https://github.com/rustwasm/wasm-pack-template') or a perhand setup: cargo new --lib hello-wasm (see. https://developer.mozilla.org/en-US/docs/WebAssembly/Rust_to_wasm)
To build a project, checkout its readme.md file.
Mostly:
- wasm-pack build --target web
- wasm-pack build --target nodejs
- wasm-pack build --target bundler
And then serving the html via serve or a bundler like vite/webpack...
- now you can open the generated /pkg file in the browser:
A wasm game of life inplementation, with drawing, zooming, starting and stopping the rendering.
A minimal example of 'wasm-pack build --web' loaded inside vanilla javascript calling javascripts alert funktion from WebAssembly using wasm_bindgen
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
pub fn alert(s: &str);
}
#[wasm_bindgen]
pub fn greet(name: &str) {
alert(&format!("Hello, {name}!"));
}
A minimal exampe of 'wasm-pack build --bundler' loaded inside of a vite project. Minimal DOMManipulation example using web_sys wasm_bindgen bindingsweb-sis
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
pub fn alert(s: &str); // bind to the browsers javascript alert function
}
#[wasm_bindgen]
pub fn greet(name: &str) -> Result<(), JsValue> {
alert(&format!(
"Hello, {name}! - lets insert something to the dom..."
));
// the web_sys crate contains predefined extern "C" byindings to most existing web-apis like
// window, document, body, etc.
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");
// Manufacture the element we're gonna append
let val = document.create_element("p")?;
val.set_inner_html(&format!("Hello from Rust: {name}!"));
body.append_child(&val)?;
Ok(())
}
Those are beatiful tutorials i used to get started: