The WebAssembly Engineer runs compute-intensive code in the browser at near-native speed. WebAssembly (WASM) is the right tool when JavaScript is genuinely too slow: image/video processing, physics simulations, cryptography, codecs, scientific computing. It is not the right tool for typical UI logic - the overhead of JS/WASM interop erases any performance gain for small computations.
Rust to WASM with wasm-bindgen
// Cargo.toml
[package]
name = "image-processor"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
image = "0.24"
[profile.release]
opt-level = 3
lto = true # Link-time optimisation - reduces binary size and improves speed
// src/lib.rs
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn grayscale(data: &[u8], width: u32, height: u32) -> Vec<u8> {
let mut output = data.to_vec();
// Process in chunks of 4 (RGBA pixels)
for chunk in output.chunks_mut(4) {
let luminance = (0.299 * chunk[0] as f32
+ 0.587 * chunk[1] as f32
+ 0.114 * chunk[2] as f32) as u8;
chunk[0] = luminance;
chunk[1] = luminance;
chunk[2] = luminance;
// chunk[3] is alpha, leave unchanged
}
output
}
// Build: wasm-pack build --target web --release
// Outputs: pkg/image_processor.js + pkg/image_processor_bg.wasm
Loading and Calling WASM from JavaScript
// Streaming instantiation (fastest - starts downloading while JS parses)
import init, { grayscale } from './pkg/image_processor.js';
let wasmReady = false;
// Initialise once on app load
async function initWasm() {
await init(); // Fetches and compiles the .wasm file
wasmReady = true;
}
initWasm();
// Process a canvas image
async function applyGrayscale(canvas: HTMLCanvasElement) {
if (!wasmReady) await initWasm();
const ctx = canvas.getContext('2d')!;
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// Pass pixel data to WASM - this copies the data into WASM memory
const result = grayscale(imageData.data, canvas.width, canvas.height);
// Copy result back and render
const outputImageData = new ImageData(
new Uint8ClampedArray(result),
canvas.width,
canvas.height
);
ctx.putImageData(outputImageData, 0, 0);
}
When to Use WebAssembly
| Use WASM | Don't use WASM |
|---|---|
| Image / video / audio processing | DOM manipulation |
| Cryptographic operations (hashing, encryption) | Network requests / fetch |
| Physics engines / simulations | Typical form validation |
| Porting existing C/C++/Rust code to the browser | Anything that can be async/non-blocking |
| Codecs (video decode, compression) | Code that runs infrequently |