WebAssembly Implementation with Claude Code
Learn about webassembly implementation using Claude Code. Practical tips and code examples included.
WebAssembly統合をClaude Codeで実現する
WebAssembly(Wasm)はブラウザでネイティブに近い速度で動作するバイナリ形式です。画像処理、暗号計算、ゲームロジックなどCPU負荷の高い処理をWebで高速に実行できます。Claude Codeを使えば、Wasmモジュールの作成から統合までスムーズに進められます。
RustからWasmモジュールを作成
> Rustで画像フィルタ処理のWasmモジュールを作成して。
> wasm-packでビルドする構成にして。
# Cargo.toml
[package]
name = "image-filter"
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"] }
// src/lib.rs
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn grayscale(pixels: &mut [u8]) {
for chunk in pixels.chunks_exact_mut(4) {
let gray = (0.299 * chunk[0] as f64
+ 0.587 * chunk[1] as f64
+ 0.114 * chunk[2] as f64) as u8;
chunk[0] = gray;
chunk[1] = gray;
chunk[2] = gray;
// chunk[3] はアルファ値、そのまま
}
}
#[wasm_bindgen]
pub fn blur(pixels: &mut [u8], width: u32, height: u32, radius: u32) {
let src = pixels.to_vec();
let r = radius as i32;
for y in 0..height as i32 {
for x in 0..width as i32 {
let mut r_sum = 0u32;
let mut g_sum = 0u32;
let mut b_sum = 0u32;
let mut count = 0u32;
for dy in -r..=r {
for dx in -r..=r {
let nx = (x + dx).clamp(0, width as i32 - 1) as usize;
let ny = (y + dy).clamp(0, height as i32 - 1) as usize;
let idx = (ny * width as usize + nx) * 4;
r_sum += src[idx] as u32;
g_sum += src[idx + 1] as u32;
b_sum += src[idx + 2] as u32;
count += 1;
}
}
let idx = (y as usize * width as usize + x as usize) * 4;
pixels[idx] = (r_sum / count) as u8;
pixels[idx + 1] = (g_sum / count) as u8;
pixels[idx + 2] = (b_sum / count) as u8;
}
}
}
JavaScriptからWasmを読み込む
> Wasmモジュールをブラウザで読み込んで、
> Canvas画像に適用する処理を書いて。
// src/wasm-loader.ts
import init, { grayscale, blur } from '../pkg/image_filter';
export async function initWasm() {
await init();
}
export async function applyGrayscale(canvas: HTMLCanvasElement) {
const ctx = canvas.getContext('2d')!;
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const pixels = new Uint8Array(imageData.data.buffer);
grayscale(pixels);
ctx.putImageData(imageData, 0, 0);
}
export async function applyBlur(
canvas: HTMLCanvasElement,
radius: number
) {
const ctx = canvas.getContext('2d')!;
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const pixels = new Uint8Array(imageData.data.buffer);
blur(pixels, canvas.width, canvas.height, radius);
ctx.putImageData(imageData, 0, 0);
}
ビルドとバンドル設定
# wasm-packでビルド
wasm-pack build --target web --out-dir pkg
# Viteでの設定
# vite.config.ts
// vite.config.ts
import { defineConfig } from 'vite';
import wasm from 'vite-plugin-wasm';
import topLevelAwait from 'vite-plugin-top-level-await';
export default defineConfig({
plugins: [wasm(), topLevelAwait()],
build: {
target: 'esnext',
},
});
パフォーマンス比較
JavaScriptとWasmの処理速度を比較してみましょう。
// benchmark.ts
async function benchmark() {
const size = 1920 * 1080 * 4;
const pixels = new Uint8Array(size);
crypto.getRandomValues(pixels);
// JavaScript版
const jsStart = performance.now();
grayscaleJS(pixels);
const jsTime = performance.now() - jsStart;
// Wasm版
const wasmStart = performance.now();
grayscale(pixels);
const wasmTime = performance.now() - wasmStart;
console.log(`JS: ${jsTime.toFixed(2)}ms`);
console.log(`Wasm: ${wasmTime.toFixed(2)}ms`);
console.log(`速度比: ${(jsTime / wasmTime).toFixed(1)}x`);
}
Full HDサイズの画像処理では、Wasm版がJavaScript版の3〜5倍高速に動作する場合があります。
Summary
WebAssemblyを活用すれば、Webアプリのパフォーマンスを大幅に向上できます。Claude Codeを使えば、RustやAssemblyScriptのコード生成からJavaScript統合まで効率的に進められます。パフォーマンス最適化ガイドやRust開発も参考にしてください。
WebAssemblyの詳細はMDN WebAssemblyガイドを参照してください。
Level up your Claude Code workflow
50 battle-tested prompt templates you can copy-paste into Claude Code right now.
Free PDF: Claude Code Cheatsheet in 5 Minutes
Key commands, shortcuts, and prompt examples on a single printable page.
About the Author
Masa
Engineer obsessed with Claude Code. Runs claudecode-lab.com, a 10-language tech media with 2,000+ pages.
Related Posts
Getting Started with Claude Code Agent SDK — Build Autonomous Agents Fast
Learn how to build autonomous AI agents with Claude Code Agent SDK. Covers setup, tool definitions, and multi-step execution with practical code examples.
The Complete Guide to Context Management in Claude Code
Learn practical techniques to maximize Claude Code's context window. Covers token optimization, conversation splitting, and CLAUDE.md usage.
Mastering Claude Code Hooks: Auto-Format, Auto-Test, and More
Mastering Claude Code Hooks: Auto-Format, Auto-Test, and More. A practical guide with code examples.