A WebAssembly primer for React developers
rustup adds the wasm target
wasm-pack builds and writes JS glue
wasm-bindgen bridges types
rustup target add wasm32-unknown-unknowncargo install wasm-pack wasm-pack build --target web --release# -> pkg/blur.js, pkg/blur_bg.wasm
use wasm_bindgen::prelude::*; #[wasm_bindgen]pub fn blur(pixels: &mut [u8], w: u32, h: u32, radius: u32) { // a box blur, run horizontally then vertically let mut tmp = pixels.to_vec(); for _ in 0..2 { box_pass(pixels, &mut tmp, w, h, radius, true); box_pass(&tmp, pixels, w, h, radius, false); } // runs at near-native speed}
import init, { blur } from '../pkg/blur'; export function BlurCanvas({ radius }: { radius: number }) { const ref = useRef<HTMLCanvasElement>(null); useEffect(() => { init().then(() => { const ctx = ref.current!.getContext('2d')!; const img = ctx.getImageData(0, 0, 640, 360); blur(img.data as unknown as Uint8Array, 640, 360, radius); ctx.putImageData(img, 0, 0); }); }, [radius]); return <canvas ref={ref} width={640} height={360} />;}
slides.ezzdinatef.com/slides/rust-in-the-browser
<iframe src="https://slides.ezzdinatef.com/embed/rust-in-the-browser" width="960" height="600" style="border:0;border-radius:12px" allow="fullscreen" title="Rust in the Browser: A WebAssembly Primer"></iframe>