- Put the
lib.rs
into src/lib.rs
and cargo.toml
in the directory root
- Compile Rust into WASM with
cargo install wasm-pack && wasm-pack build --target web
or if you use Docker docker run -it -v "$PWD":/app -w /app rust bash -c "cargo install wasm-pack && wasm-pack build --target web"
- Now pkg directory contains the lib
- Use it on your browser:
import init, { sum, resize } from "./pkg/app.js";
await init();
console.log(sum(1, 2));
const imageInput = document.getElementById('imageInput');
imageInput.addEventListener('change', async (e) => {
const file = e.target.files[0];
const arrayBuffer = await file.arrayBuffer();
const uint8Array = new Uint8Array(arrayBuffer);
const resizedImage = resize(uint8Array, 400, 400);
const blob = new Blob([resizedImage], { type: 'image/png' });
const url = URL.createObjectURL(blob);
const img = document.createElement('img');
img.src = url;
document.body.appendChild(img);
});