High-performance WebAssembly modules using Rust for CPU-intensive browser and Node.js applications
# WebAssembly with Rust Integration for Google Antigravity
Build high-performance WebAssembly modules using Rust with Google Antigravity's Gemini 3 engine. This guide covers wasm-bindgen, memory management, JavaScript interop, and optimization techniques.
## Rust Library Setup
```toml
# Cargo.toml
[package]
name = "image-processor"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
wasm-bindgen = "0.2"
js-sys = "0.3"
web-sys = { version = "0.3", features = [
"console",
"ImageData",
"CanvasRenderingContext2d"
]}
serde = { version = "1.0", features = ["derive"] }
serde-wasm-bindgen = "0.6"
getrandom = { version = "0.2", features = ["js"] }
[profile.release]
opt-level = "s"
lto = true
```
## WebAssembly Module Implementation
```rust
// src/lib.rs
use wasm_bindgen::prelude::*;
use web_sys::console;
#[wasm_bindgen]
pub struct ImageProcessor {
width: u32,
height: u32,
pixels: Vec<u8>,
}
#[wasm_bindgen]
impl ImageProcessor {
#[wasm_bindgen(constructor)]
pub fn new(width: u32, height: u32) -> Self {
console::log_1(&"ImageProcessor initialized".into());
Self {
width,
height,
pixels: vec![0; (width * height * 4) as usize],
}
}
pub fn load_pixels(&mut self, data: &[u8]) {
self.pixels = data.to_vec();
}
pub fn get_pixels(&self) -> Vec<u8> {
self.pixels.clone()
}
pub fn apply_grayscale(&mut self) {
for chunk in self.pixels.chunks_mut(4) {
let gray = (0.299 * chunk[0] as f32
+ 0.587 * chunk[1] as f32
+ 0.114 * chunk[2] as f32) as u8;
chunk[0] = gray;
chunk[1] = gray;
chunk[2] = gray;
}
}
pub fn apply_blur(&mut self, radius: u32) {
let mut output = vec![0u8; self.pixels.len()];
let kernel_size = (radius * 2 + 1) as i32;
let kernel_area = (kernel_size * kernel_size) as f32;
for y in 0..self.height as i32 {
for x in 0..self.width as i32 {
let mut r_sum = 0f32;
let mut g_sum = 0f32;
let mut b_sum = 0f32;
for ky in -(radius as i32)..=(radius as i32) {
for kx in -(radius as i32)..=(radius as i32) {
let px = (x + kx).clamp(0, self.width as i32 - 1);
let py = (y + ky).clamp(0, self.height as i32 - 1);
let idx = ((py * self.width as i32 + px) * 4) as usize;
r_sum += self.pixels[idx] as f32;
g_sum += self.pixels[idx + 1] as f32;
b_sum += self.pixels[idx + 2] as f32;
}
}
let out_idx = ((y * self.width as i32 + x) * 4) as usize;
output[out_idx] = (r_sum / kernel_area) as u8;
output[out_idx + 1] = (g_sum / kernel_area) as u8;
output[out_idx + 2] = (b_sum / kernel_area) as u8;
output[out_idx + 3] = self.pixels[out_idx + 3];
}
}
self.pixels = output;
}
pub fn adjust_brightness(&mut self, factor: f32) {
for chunk in self.pixels.chunks_mut(4) {
chunk[0] = ((chunk[0] as f32 * factor).min(255.0)) as u8;
chunk[1] = ((chunk[1] as f32 * factor).min(255.0)) as u8;
chunk[2] = ((chunk[2] as f32 * factor).min(255.0)) as u8;
}
}
}
#[wasm_bindgen]
pub fn fibonacci(n: u32) -> u64 {
match n {
0 => 0,
1 => 1,
_ => {
let mut a = 0u64;
let mut b = 1u64;
for _ in 2..=n {
let temp = a + b;
a = b;
b = temp;
}
b
}
}
}
```
## JavaScript Integration
```typescript
// src/wasm-loader.ts
import init, { ImageProcessor, fibonacci } from '../pkg/image_processor';
let wasmInitialized = false;
export async function initWasm(): Promise<void> {
if (!wasmInitialized) {
await init();
wasmInitialized = true;
}
}
export async function processImage(
imageData: ImageData,
operations: Array<{ type: string; value?: number }>
): Promise<ImageData> {
await initWasm();
const processor = new ImageProcessor(imageData.width, imageData.height);
processor.load_pixels(new Uint8Array(imageData.data.buffer));
for (const op of operations) {
switch (op.type) {
case 'grayscale':
processor.apply_grayscale();
break;
case 'blur':
processor.apply_blur(op.value ?? 2);
break;
case 'brightness':
processor.adjust_brightness(op.value ?? 1.0);
break;
}
}
const resultPixels = processor.get_pixels();
return new ImageData(
new Uint8ClampedArray(resultPixels),
imageData.width,
imageData.height
);
}
export async function computeFibonacci(n: number): Promise<bigint> {
await initWasm();
return BigInt(fibonacci(n));
}
```
## Best Practices
Google Antigravity's Gemini 3 engine recommends these WebAssembly patterns: Use wasm-bindgen for seamless JavaScript interop. Minimize data copying between JavaScript and WASM by using shared memory views. Enable LTO and size optimization for smaller bundles. Use web-sys for direct DOM access when needed. Implement proper error handling with Result types that convert to JavaScript exceptions.This WebAssembly prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their webassembly implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For WebAssembly projects, consider mentioning your framework version, coding style, and any specific libraries you're using.