In the bridge lesson, sending "Renée" to Wasm took a TextEncoder, an address and a byte length you worked out yourself. In Rust, wasm-bindgen does that work. It generates go-between code (glue) on both sides so that Rust functions can take and return strings, JS objects and closures, not just numbers. On top of it sit two crates: js-sys for JavaScript's built-in objects (Array, Date, Math, Promise) and web-sys for Web APIs (console, document, canvas, fetch).
A guest from abroad staying at Mist Homestay usually comes with a guide who translates both ways and carries their luggage. The guide brings a general phrasebook for everyday talk, and maps of the sights that are bought one sheet at a time, by destination. The guest is the Rust code, the homestay is the browser, the guide is wasm-bindgen, the phrasebook is js-sys, and the map sheets are web-sys features: to go to the canvas, buy the canvas sheet.
The project: mist-canvas
The toolchain is the same as in the wasm-pack lesson (rustc 1.99.0, wasm-pack 0.15.0, wasm-bindgen 0.2.129), plus web-sys 0.3.106:
[dependencies]
wasm-bindgen = "0.2"
web-sys = { version = "0.3", features = ["console", "CanvasRenderingContext2d"] }
use wasm_bindgen::prelude::*;
use web_sys::{console, CanvasRenderingContext2d};
/// &str in, String out.
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
format!("Welcome to Mist Homestay, {name}!")
}
/// console.log from Rust.
#[wasm_bindgen]
pub fn log(message: &str) {
console::log_1(&JsValue::from_str(message));
}
/// The total price of three rooms for some nights, drawn on a canvas.
#[wasm_bindgen(js_name = drawPrices)]
pub fn draw_prices(ctx: &CanvasRenderingContext2d, nights: i32) {
let rooms = [("Terrace", 3_500), ("Attic", 2_750), ("Garden", 4_250)]; // cents
ctx.clear_rect(0.0, 0.0, 300.0, 140.0);
ctx.set_font("13px sans-serif");
for (i, (name, price)) in rooms.iter().enumerate() {
let total = nights * price;
let y = 12.0 + i as f64 * 42.0;
ctx.set_fill_style_str("#7aa6d6");
ctx.fill_rect(0.0, y, total as f64 / 100.0, 28.0); // $1 = 1 pixel
ctx.set_fill_style_str("#1d2733");
ctx.fill_text(&format!("{name}: ${}.{:02}", total / 100, total % 100), 6.0, y + 19.0).unwrap();
}
console::log_1(&format!("drawPrices: {nights} nights").into());
}
(stayPrice from the wasm-pack lesson is in this crate too.) On the page:
import init, { greet, log, drawPrices } from './pkg/mist_canvas.js';
await init();
console.log(greet('Renée')); // Welcome to Mist Homestay, Renée!
log('Hello from Rust'); // shows up in the console, sent from Rust
const ctx = document.querySelector('canvas').getContext('2d');
drawPrices(ctx, 2); // three price bars on the canvas
&strandStringin Rust becomestringin JS. Copying the UTF-8 bytes, as in the bridge lesson, is now done by the glue.console::log_1is web-sys's function forconsole.logwith one argument (log_2for two, and so on).JsValueis any JS value held by Rust.&CanvasRenderingContext2dreceivesctxfrom JS. Its methods are written Rust-style:fillRectbecomesfill_rect, and thefillStyleproperty is set withset_fill_style_str.- Methods that can fail in JS (such as
fillText) returnResult<(), JsValue>.unwrap()stops the program on failure; in real code, hand the error back to JS with?. - The canvas can also be fetched from Rust through
web_sys::window()anddocument(), as long as theWindow,DocumentandHtmlCanvasElementfeatures are turned on.
What wasm-bindgen generates
wasm-pack build --target web writes pkg/mist_canvas.js (11,776 bytes). This is the glue for greet and drawPrices:
export function greet(name) {
let deferred2_0;
let deferred2_1;
try {
const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.greet(ptr0, len0);
deferred2_0 = ret[0];
deferred2_1 = ret[1];
return getStringFromWasm0(ret[0], ret[1]);
} finally {
wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
}
}
export function drawPrices(ctx, nights) {
wasm.drawPrices(ctx, nights);
}
And part of the imports that Rust calls:
__wbg_fillRect_0ef59adb9acb7d06: function(arg0, arg1, arg2, arg3, arg4) {
arg0.fillRect(arg1, arg2, arg3, arg4);
},
__wbg_log_17c30ef363c61cf4: function(arg0) {
console.log(arg0);
},
- A string going in:
passStringToWasm0reserves room with__wbindgen_malloc, writes the UTF-8 bytes, then sends a pointer and a length. For"Renée", the glue reserves 5 bytes (the string's length), meetsé, grows it to 9, then trims it to 6. - A string coming out:
wasm.greetreturns two numbers at once (a pointer and a length). The glue decodes the bytes into a JS string, then__wbindgen_freereleases the space infinally. - A JS object:
ctxis sent as it is, as anexternref, with no copy. When Rust callsfill_rect, Wasm calls the__wbg_fillRect_...import, and that import runsarg0.fillRect(...). OnedrawPrices(ctx, 2)= 16 calls from Wasm to JS: 14 to the canvas, and 2 for console.log (turning the text into a JS string, thenlog). - Suffixes like
_0ef59adb9acb7d06are generated by wasm-bindgen. The glue and the.wasmmust come from the same build; never mix files from two builds.
js-sys and web-sys
- js-sys: bindings to JavaScript's built-in objects, which exist in every JS environment:
Array,Object,Date,Math,JSON,Promise,Uint8Array. No features needed. For example:js_sys::Date::now(). - web-sys: bindings to the Web APIs a browser provides:
Window,Document,HtmlCanvasElement,CanvasRenderingContext2d,console,Request,Response. Every type is one Cargo feature, and only the ones turned on are compiled. Forget the feature and rustc refuses:
error[E0432]: unresolved import `web_sys::CanvasRenderingContext2d`
--> src/lib.rs:2:24
|
2 | use web_sys::{console, CanvasRenderingContext2d};
| ^^^^^^^^^^^^^^^^^^^^^^^^ no `CanvasRenderingContext2d` in the root
The web-sys documentation on docs.rs lists, for every type, which features it needs.
📌 Closures: Rust as an event listener
A Rust function can become a JS callback through Closure. This needs the HtmlElement and EventTarget features:
#[wasm_bindgen(js_name = attachButton)]
pub fn attach_button(button: &web_sys::HtmlElement) -> Result<(), JsValue> {
let click = Closure::<dyn FnMut()>::new(|| console::log_1(&"Book button clicked".into()));
button.add_event_listener_with_callback("click", click.as_ref().unchecked_ref())?;
click.forget(); // let the closure live as long as the page
Ok(())
}
Closure::newwraps a Rust closure as a JS function.as_ref().unchecked_ref()turns it into theFunctiontype thatadd_event_listener_with_callbackasks for.- If
clickis dropped when the function ends, the listener stays attached, and the next click fails:Error: closure invoked recursively or after being dropped. forget()keeps the closure alive forever. For a listener attached once, that is fine. For listeners attached and removed again and again, keep theClosure, then drop it afterremove_event_listener, so its memory does not leak.
The size cost of the glue
Measured on one build of this crate with wasm-pack build --target web (release), adding one function per row. With other text or prices in the code, your build can differ by a few bytes:
| What the crate holds | .wasm |
.js glue |
|---|---|---|
stayPrice only |
13,590 bytes | 4,122 bytes |
+ greet (a String in and out) |
15,497 bytes | 6,994 bytes |
+ log (web-sys console) |
19,022 bytes | 7,701 bytes |
+ drawPrices (web-sys canvas) |
22,102 bytes | 11,776 bytes |
+ attachButton (Closure) |
23,049 bytes | 14,091 bytes |
From 13,590 bytes, those three extra functions take the .wasm to about 22 KB (22,102 bytes, 9,894 bytes gzipped). The base is already 13 KB for one multiplication: the allocator, the externref table and panic handling. format! for the text adds Rust's formatting machinery. web-sys itself holds thousands of APIs, but only the ones you call come along. With opt-level = "z", lto = true and codegen-units = 1 in [profile.release], the drawPrices version drops to 20,569 bytes. The Lab on this page runs that build.
📌 Who maintains it
The rustwasm GitHub organisation was archived in 2025. wasm-bindgen, js-sys and web-sys are now maintained in the wasm-bindgen organisation and keep shipping releases; the story is in the lesson "Wasm from Rust (wasm-pack)".
⚠️ Errors and costs that catch people out
- Forgetting a web-sys feature.
error[E0432]: unresolved importeven though the crate is there. Add the type's name tofeatures. - A dropped closure. The listener stays attached but its contents are gone:
Error: closure invoked recursively or after being dropped. Useforget()or keep theClosure. - Calling a function before
await init(). The glue has no Wasm module yet. - Thinking web-sys is free. One API type can add a few KB. Turn on only the features you really use.
TL;DR: wasm-bindgen generates glue on both sides: &str/String are copied as UTF-8 bytes (passStringToWasm0, getStringFromWasm0, then __wbindgen_free), JS objects such as ctx cross as they are, as an externref, and every Web API method Rust calls becomes a JS import (__wbg_fillRect_...). js-sys is for JS built-ins (Array, Date, Math, Promise) with no features; web-sys is for Web APIs (console, document, canvas, fetch), one Cargo feature per type, and a missing feature means error[E0432]. console::log_1 for console.log, CanvasRenderingContext2d with fill_rect and set_fill_style_str to draw. Closure::new makes a JS callback; dropping it too early means closure invoked recursively or after being dropped, so forget() it or keep it. The cost: stayPrice alone is 13,590 bytes, with strings, console and canvas 22,102 bytes (20,569 with opt-level = "z" and LTO). wasm-bindgen is maintained by the wasm-bindgen organisation since 2025.
⚡ A string in, a String out
Write:
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
format!("Welcome to Mist Homestay, {name}!")
}
Meaning: &str and String in Rust become string in JS. The glue wasm-bindgen generates copies the UTF-8 bytes: in through passStringToWasm0, out through getStringFromWasm0, and then the space is released with __wbindgen_free.
⚡ js-sys and web-sys
Write:
[dependencies]
wasm-bindgen = "0.2"
web-sys = { version = "0.3", features = ["console", "CanvasRenderingContext2d"] }
Meaning: js-sys holds bindings to JavaScript's built-in objects (Array, Date, Math, Promise), with no features. web-sys holds bindings to Web APIs (console, document, canvas, fetch), one Cargo feature per type. Forget the feature and rustc refuses with error[E0432]: unresolved import.
⚡ JS objects cross as they are
Guess first: when drawPrices(ctx, 2) is called, is ctx copied into Wasm memory?
No. ctx is sent as it is, as an externref. Every time Rust calls fill_rect, Wasm calls the __wbg_fillRect_... import, and that import runs arg0.fillRect(...).
Meaning: In Rust, Web API methods are written Rust-style: fillRect becomes fill_rect, and fillStyle is set with set_fill_style_str. One drawPrices(ctx, 2) = 16 calls from Wasm to JS.
⚡ Don't drop the closure
Write:
let click = Closure::<dyn FnMut()>::new(|| console::log_1(&"Book button clicked".into()));
button.add_event_listener_with_callback("click", click.as_ref().unchecked_ref())?;
click.forget(); // let the closure live as long as the page
Meaning: Closure::new wraps a Rust closure as a JS function. If click is dropped when the function ends, the next click fails with Error: closure invoked recursively or after being dropped.