WebGL2 wrapper for Rust and WebAssembly
Demo: https://top-5.github.io/webglue/
webglue is a WebGL2 wrapper for Rust that compiles to WebAssembly, providing an OpenGL-like API for browser-based 3D graphics.
⚠️ This crate is WASM-only and must be compiled with--target wasm32-unknown-unknown.
Built on top of glow, webglue translates familiar OpenGL function calls into WebGL2 operations, with a handle registry to bridge between u32 IDs and glow's opaque handles.
- 🎯 70+ WebGL2 functions - Comprehensive rendering pipeline
- 🚀 Instanced rendering - DrawElementsInstanced for high-performance graphics
- 📐 Matrix math library - Perspective, lookAt, rotate, translate, scale operations
- 📦 Optional GLTF support - Load and render GLTF/GLB 3D models
- 🔄 Handle-based registry - Bridges u32 IDs ↔ glow's opaque WebGL handles
- ⚡ Optimized builds - ~105KB WASM (gzipped with LTO)
[dependencies]
webglue = "0.1"
# Optional: Enable GLTF model loading
webglue = { version = "0.1", features = ["gltf"] }cargo build --target wasm32-unknown-unknown --release
# Or use wasm-pack
wasm-pack build --target web --releaseuse webglue as gl;
unsafe {
// Initialize once with WebGL2 context
gl::init_with_webgl2_context(webgl2_context);
// Create and bind buffer
let mut vbo = 0;
gl::GenBuffers(1, &mut vbo);
gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
// Upload vertex data
gl::BufferData(
gl::ARRAY_BUFFER,
(vertices.len() * 4) as isize,
vertices.as_ptr() as *const _,
gl::STATIC_DRAW
);
// Setup vertex attributes
gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, 0, std::ptr::null());
gl::EnableVertexAttribArray(0);
// Draw
gl::DrawArrays(gl::TRIANGLES, 0, vertex_count as i32);
}GenBuffers,DeleteBuffers,BindBuffer,BufferData,BufferSubData
GenVertexArrays,DeleteVertexArrays,BindVertexArrayEnableVertexAttribArray,DisableVertexAttribArrayVertexAttribPointer,VertexAttribDivisor
CreateShader,DeleteShader,ShaderSource,CompileShaderCreateProgram,DeleteProgram,AttachShader,LinkProgram,UseProgramGetShaderiv,GetShaderInfoLog,GetProgramiv,GetProgramInfoLog
GetUniformLocationUniform1f,Uniform1i,Uniform2f,Uniform3f,Uniform4fUniform3fv,Uniform4fvUniformMatrix3fv,UniformMatrix4fv
GenTextures,DeleteTextures,BindTexture,ActiveTextureTexImage2D,TexSubImage2D,TexParameteriGenerateMipmap,PixelStorei
DrawArrays,DrawElements,DrawElementsInstanced⚡
GenFramebuffers,BindFramebuffer,FramebufferTexture2DGenRenderbuffers,BindRenderbuffer,RenderbufferStorage
Enable,Disable,Viewport,Clear,ClearColorDepthMask,BlendFunc,BlendFuncSeparate,FinishReadPixels,PointSize(stub)
GetError,GetGraphicsResetStatus,GetIntegerv,GetString,GetStringi
Total: 70+ functions ✅
┌──────────────────────────────────────┐
│ Your Rust/WASM Application │
│ (OpenGL-style function calls) │
└────────────────┬─────────────────────┘
│
┌──────▼─────────┐
│ webglue │
│ wrapper.rs │
└──────┬─────────┘
│
┌──────▼─────────┐
│ Handle Registry│
│ (u32 ↔ Handle) │
└──────┬─────────┘
│
┌──────▼─────────┐
│ glow │
│ (Rust→WebGL) │
└──────┬─────────┘
│
┌──────▼─────────┐
│ WebGL2 │
│ (Browser) │
└────────────────┘
WebGL via glow uses opaque handles (glow::Buffer, glow::Program, etc.), not u32 IDs like desktop OpenGL. The registry:
- Translates u32 IDs ↔ opaque glow handles
- Maintains OpenGL-style API compatibility
- Uses
slabfor efficient O(1) lookups - Minimal overhead - direct index-to-handle mapping
Built-in 4x4 matrix operations for 3D graphics:
use webglue::math::*;
// Projection matrix
let proj = perspective(45.0_f32.to_radians(), aspect_ratio, 0.1, 100.0);
// View matrix
let view = look_at(
&[0.0, 2.0, 5.0], // camera position
&[0.0, 0.0, 0.0], // look at target
&[0.0, 1.0, 0.0], // up vector
);
// Model transformations
let model = Mat4::identity()
.rotate_y(angle)
.translate(&[x, y, z])
.scale(&[sx, sy, sz]);
// Combined MVP matrix
let mvp = proj * view * model;
// Upload to shader uniform
unsafe {
gl::UniformMatrix4fv(mvp_loc, 1, gl::FALSE, mvp.as_ptr());
}Available operations:
perspective(),orthographic()- Projection matriceslook_at()- View matrix from camera parametersMat4::identity(),translate(),rotate_x/y/z(),scale()- Transforms- Matrix multiplication with
*operator
With the gltf feature enabled, you can load and render 3D models:
use webglue::gltf_model::GltfModel;
// Load GLTF model from URL
let model = GltfModel::load_from_url("models/scene.gltf").await?;
// Render in your draw loop
unsafe {
model.render();
}Supports:
- GLTF 2.0 and GLB binary format
- Embedded textures and images
- Multiple meshes and materials
- Extensions:
KHR_lights_punctual,extras,names
WebGL2 instanced rendering provides massive performance gains for repeated geometry:
| Rendering Method | Draw Calls | Objects | Performance |
|---|---|---|---|
| Individual DrawArrays | 1,000 | 1,000 | ~15-30 FPS |
| DrawElementsInstanced | 1 | 1,000 | 60 FPS |
| DrawElementsInstanced | 1 | 10,000 | 60 FPS |
Speedup: 100-500x for scenes with many similar objects 🚀
The repository includes a comprehensive Vite-based demo application in demo/:
cd demo
npm install
npm run devLive Demo: Opens interactive showcase with multiple samples:
- Textured Sphere - Earth texture mapping with UV coordinates
- Textured Cube - 3D cube with image textures
- Colored Cube - RGB vertex colors
- Instanced Rendering - 1000+ objects in a single draw call
- GLTF Models - Load and render 3D scenes (Box, FlightHelmet, Head)
- Primitives - Sphere, cone geometry generation
- Matrix Transforms - Rotation, translation, scaling
- Blend Modes - BlendFunc and BlendFuncSeparate demos
# Build library for WebAssembly
cargo build --target wasm32-unknown-unknown --release
# With GLTF feature
cargo build --target wasm32-unknown-unknown --release --features gltf
# Run unit tests (on host target)
cargo test --lib# Install wasm-pack
cargo install wasm-pack
# Build for web
wasm-pack build --target web --release --out-dir pkg
# The pkg/ directory is ready to import in JavaScript:
# import init, * as wasm from './pkg/webglue.js';Release builds are optimized for size:
- LTO enabled - Link-time optimization
- Single codegen unit - Maximum optimization
- Result: ~105KB WASM (gzipped)
Cargo.toml configuration:
[profile.release]
opt-level = 3
lto = true
codegen-units = 1| Dependency | Current | Latest | Notes |
|---|---|---|---|
glow |
0.16 | 0.16.0 | ✅ Up to date |
slab |
0.4 | 0.4.11 | ✅ Up to date |
gltf |
1.4 | 1.4.1 | |
wasm-bindgen |
0.2 | 0.2.104 | |
web-sys |
0.3 | 0.3.81 |
Run
cargo updateto get latest compatible versions within semver ranges.
Copyright © 2025 Top-5
Licensed under the Apache License, Version 2.0 (LICENSE or http://www.apache.org/licenses/LICENSE-2.0)
Contributions welcome! Priority areas:
- 🔧 Update to latest dependency versions (gltf 1.4.1, wasm-bindgen 0.2.104, etc.)
- 📚 More WebGL2 functions (additional state management, queries)
- 🧮 Extended math utilities (quaternions, frustum culling)
- 📦 More GLTF features (animations, skinning)
- 📖 Documentation and examples
- 🧪 Test coverage improvements
Built on top of excellent Rust crates:
glow- OpenGL/WebGL bindingsgltf- GLTF 2.0 loaderslab- Efficient handle registrywasm-bindgen- Rust/WASM/JS glue