21. WebGPU and Choosing Your Graphics Stack
“WebGL asked the GPU to paint. WebGPU asks the GPU to think.”
The story: from waiter to kitchen manager
Section titled “The story: from waiter to kitchen manager”In WebGL, you talk to the GPU like a customer talking to a waiter, one request at a time: “Use this plate. Now this sauce. Now draw. Now this other plate. Draw.” The waiter checks each request, runs to the kitchen, and runs back. It works, it’s forgiving, and the waiter spends a lot of time running.
In WebGPU, you’re the kitchen manager. Before service starts, you prepare recipes (pipelines) and mise en place (bind groups) in advance. During service, you write down the evening’s whole sequence of orders in a notebook (a command encoder) and hand the finished notebook to the kitchen in one go (submit). The kitchen doesn’t have to second-guess anything; it’s all been validated and laid out. Service is faster and more predictable — and you can ask the kitchen to do things that aren’t plating at all, like prepping a thousand portions of chutney in parallel (compute).
That’s the shift: from an implicit, chatty, global-state API designed in the 2000s to an explicit, prepared, batched API modelled on the native graphics APIs of the 2010s.
Why WebGPU exists
Section titled “Why WebGPU exists”WebGL is based on OpenGL ES, whose design dates from an era of fixed hardware and single-threaded drivers. Native platforms moved on: Vulkan (cross-platform), Metal (Apple), and Direct3D 12 (Microsoft) are explicit APIs. They make the application describe its work up front — pipeline state, resource layouts, command buffers — so the driver does less guessing and validation at draw time, CPU overhead drops, and multi-threaded command recording becomes possible. They also treat general-purpose compute as first-class.
Meanwhile, browsers implementing WebGL were translating OpenGL-style calls onto these modern APIs (Chrome’s ANGLE translates to D3D11, Metal or Vulkan), paying for an impedance mismatch. WebGPU is a new web API designed for the modern APIs from the start, built jointly by browser vendors in the W3C’s GPU for the Web group, with its own shading language, WGSL.
What’s different
Section titled “What’s different”| Concept | WebGL | WebGPU |
|---|---|---|
| State | Global, implicit state machine (bind, then draw) | Explicit objects: pipelines bundle shader + vertex layout + blend/depth state; immutable once created |
| Resources to shaders | Uniform locations, bound textures | Bind groups: a pre-validated set of buffers/textures/samplers matching a layout |
| Issuing work | Immediate calls | Command encoder records passes → command buffer → queue.submit() |
| Validation | On every call | Mostly at creation time; cheap at submit |
| Compute | Hacks via fragment shaders / transform feedback | Compute shaders and compute passes, first-class |
| Shading language | GLSL ES | WGSL |
| Errors | getError() polling |
Error scopes, async, detailed messages |
| Async | Mostly sync | Adapter/device requests, buffer mapping are async |
Compute shaders: the big unlock
Section titled “Compute shaders: the big unlock”A compute shader runs your function across a grid of invocations grouped into workgroups, reading and writing storage buffers and textures — no triangles, no pixels required. That’s general-purpose parallel computing (GPGPU) on the web: particle simulations, physics, image processing, generating geometry, culling, sorting, and machine learning inference. In WebGL you could fake some of this by encoding data in textures and “drawing” a full-screen quad; in WebGPU it’s direct, and data can stay on the GPU between compute and render passes.
WGSL (WebGPU Shading Language) is a Rust-flavoured, strongly typed language designed to translate safely to SPIR-V, Metal Shading Language and HLSL:
@vertexfn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f { var p = array<vec2f, 3>(vec2f(0.0, 0.8), vec2f(-0.7, -0.6), vec2f(0.7, -0.6)); return vec4f(p[i], 0.0, 1.0);}@fragmentfn fs() -> @location(0) vec4f { return vec4f(1.0, 0.55, 0.1, 1.0); }Browser support
Section titled “Browser support”As of late 2026: WebGPU shipped in Chrome and Edge on Windows, macOS and ChromeOS in 2023, followed by Android and progressively Linux; Safari shipped it with its 2025 releases across macOS, iOS and iPadOS; Firefox shipped it on Windows in 2025 and has been rolling it out to other platforms since. The specification is at W3C Candidate Recommendation stage. Coverage is now broad on modern devices but not universal — older devices, older OS versions, some GPUs and blocklisted drivers don’t get it, and even where the API exists, requestAdapter() can return null.
So: feature-detect, and keep a fallback (WebGL2, or a non-GPU path) for anything users depend on. Treat WebGPU as a progressive enhancement for most consumer-facing work.
if (!navigator.gpu) return useWebGLFallback();const adapter = await navigator.gpu.requestAdapter();if (!adapter) return useWebGLFallback();const device = await adapter.requestDevice();A minimal WebGPU triangle
Section titled “A minimal WebGPU triangle”const context = canvas.getContext('webgpu');const format = navigator.gpu.getPreferredCanvasFormat();context.configure({ device, format });
const module = device.createShaderModule({ code: WGSL_SOURCE }); // the vs/fs aboveconst pipeline = device.createRenderPipeline({ layout: 'auto', vertex: { module, entryPoint: 'vs' }, fragment: { module, entryPoint: 'fs', targets: [{ format }] },});
function frame() { const encoder = device.createCommandEncoder(); const pass = encoder.beginRenderPass({ colorAttachments: [{ view: context.getCurrentTexture().createView(), clearValue: [0.04, 0.05, 0.07, 1], loadOp: 'clear', storeOp: 'store' }], }); pass.setPipeline(pipeline); pass.draw(3); // three vertices, positions generated in the shader pass.end(); device.queue.submit([encoder.finish()]); requestAnimationFrame(frame);}requestAnimationFrame(frame);Compared with WebGL’s triangle: more setup (adapter, device, pipeline), but notice how the per-frame code is a short, linear recording — no global state to bind, nothing re-validated per call.
A minimal compute example: particles
Section titled “A minimal compute example: particles”The shape of a GPU particle simulation: a storage buffer of particle positions and velocities; a compute shader that updates every particle in parallel; a render pass that draws them, reading the same buffer. No data ever goes back to JavaScript.
struct Particle { pos: vec2f, vel: vec2f };@group(0) @binding(0) var<storage, read_write> ps: array<Particle>;@group(0) @binding(1) var<uniform> dt: f32;
@compute @workgroup_size(64)fn step(@builtin(global_invocation_id) id: vec3u) { let i = id.x; if (i >= arrayLength(&ps)) { return; } var p = ps[i]; p.vel.y -= 0.5 * dt; // gravity p.pos += p.vel * dt; if (p.pos.y < -1.0) { p.pos.y = -1.0; p.vel.y *= -0.8; } // bounce ps[i] = p;}// each frame: one compute pass, then a render pass that reads the same bufferconst pass = encoder.beginComputePass();pass.setPipeline(computePipeline);pass.setBindGroup(0, particleBindGroup);pass.dispatchWorkgroups(Math.ceil(count / 64)); // 64 invocations per workgrouppass.end();// …render pass draws `count` instances, vertex shader reads ps[instance_index]A million particles updated per frame is routine on a decent GPU; on the CPU in JavaScript, you’d be lucky to manage a small fraction of that at 60 FPS without blocking the main thread.
Three.js on WebGPU, and TSL
Section titled “Three.js on WebGPU, and TSL”Three.js has a WebGPURenderer that targets WebGPU and can fall back to a WebGL2 backend when WebGPU isn’t available. Alongside it comes TSL (Three.js Shading Language): you write shaders as JavaScript node graphs (color(…).mul(texture(map, uv()))…), and Three.js compiles them to WGSL or GLSL depending on the backend. TSL also exposes compute, so you can write a particle simulation in JavaScript-flavoured nodes that runs as a WebGPU compute shader.
For the author’s maths-learning site: the WebGL renderer is entirely adequate for a typical maths visualization (surfaces, vectors, labelled axes). WebGPURenderer with TSL becomes attractive for heavy, dynamic geometry — say, evaluating a parametric surface or a vector field on a large grid every frame via compute — with the fallback handling devices without WebGPU.
WebGPU for ML in the browser (briefly)
Section titled “WebGPU for ML in the browser (briefly)”Neural network inference is mostly big matrix multiplications — perfect for compute shaders. Libraries such as ONNX Runtime Web, Transformers.js and WebLLM use WebGPU to run models (image classification, speech recognition, embeddings, even small language models) directly in the browser: no server cost, data stays on the device, works offline. The constraints are real: model downloads are tens to thousands of megabytes, GPU memory limits apply, and performance varies enormously by device. There’s also a separate in-progress API, WebNN, aimed at using dedicated neural accelerators. For product work: great for privacy-sensitive, latency-sensitive features on capable devices, with a server fallback.
The decision guide
Section titled “The decision guide”Here’s the question you’ll be asked in design reviews: what should we draw this with? Options, from lightest to heaviest:
- CSS (including transforms, gradients, masks,
backdrop-filter) — for UI chrome, simple effects, transitions. Free accessibility and layout; expensive effects (big live blurs) cost GPU. - SVG — for icons, illustrations, diagrams, charts with up to hundreds or low thousands of elements. Retained mode, accessible, crisp at any size, styleable with CSS. Slows down with many thousands of nodes or heavy filters.
- Canvas 2D — for charts and visualizations with thousands to tens of thousands of elements, simple games, image processing. Immediate mode; you handle hit-testing and accessibility.
- WebGL / WebGL2 (often via Three.js) — for 3D, custom shaders, large numbers of animated objects, image effects with full control. Universal support (with software fallback caveats).
- WebGPU — for compute-heavy workloads (simulations, ML, very large datasets), modern rendering techniques, lower CPU overhead at high draw counts. Progressive enhancement with a fallback.
- CSS/SVG filters — for effects on DOM content (blur, displacement) without leaving the DOM. Convenient; costs scale with area and frame rate, and some paths are CPU-heavy.
Applied: data visualization
Section titled “Applied: data visualization”- A dashboard card with a line chart of 30 points: SVG (accessible, styleable, tiny).
- A time series with 50,000 points: Canvas 2D or WebGL (a charting library with a WebGL renderer), with a data table or summary for accessibility.
- An interactive map of a million points: WebGL, or WebGPU with compute-based aggregation, with fallback.
Applied: a 3D maths visualization site
Section titled “Applied: a 3D maths visualization site”- Core 3D scenes (surfaces, vectors, transformations): Three.js on WebGL2 — universal, mature, well-documented. Render scale tuned per device tier; pause when off-screen.
- Labels, equations, controls: DOM (accessible, crisp text, real sliders) layered over the canvas, not text drawn in 3D.
- Heavy dynamic computations (large vector fields, iterative systems): WebGPU compute via TSL, progressive enhancement; fall back to coarser grids on WebGL.
- 2D diagrams and graphs inside lessons: SVG.
Applied: glassmorphism and lens effects (the author’s audit project)
Section titled “Applied: glassmorphism and lens effects (the author’s audit project)”- Static glass (translucent panel over a static or slowly changing background): CSS with a solid-ish translucent fill; even better, a pre-blurred backdrop image for the area behind panels instead of live
backdrop-filter. Near-zero runtime cost. - A few live glass surfaces over moving content: CSS
backdrop-filterwith modest radius, limited count, paused off-screen. - Lens/refraction distortion (true displacement, chromatic aberration): one shared WebGL2 context rendering all surfaces via viewports, with the wallpaper as one shared texture, animation driven by uniforms (not DOM attribute updates), rendered at reduced resolution on weak devices, paused when off-screen, and a static fallback tier — not an SVG filter per surface in separate iframes.
- WebGPU for the lens pipeline only if you need compute (e.g., generating displacement maps on the GPU at startup instead of the 52 ms CPU task) — and still behind detection with a WebGL fallback.
What you now know
Section titled “What you now know”You can explain why WebGPU exists and how it differs from WebGL (pipelines, bind groups, command encoders, compute, WGSL); describe its support situation and feature-detect it; read a minimal WebGPU triangle and a compute particle simulation; place Three.js’s WebGPURenderer and TSL; describe the promise and limits of ML in the browser; and choose between CSS, SVG, Canvas 2D, WebGL and WebGPU for data viz, 3D maths, and glass/lens effects with budgets and fallbacks.
Self-quiz
Section titled “Self-quiz”1. What does a WebGPU render pipeline bundle?
Shader modules and entry points, vertex layout, primitive topology, blend/depth/stencil state and target formats — immutable once created.
2. Why is WebGPU’s per-frame CPU cost lower than WebGL’s?
Validation happens mostly at creation; per-frame work is recording pre-validated commands into a buffer and submitting once.
3. What can compute shaders do that render pipelines can’t easily?
General parallel computation on buffers (simulations, ML, sorting, culling) without drawing triangles.
4. Can you assume WebGPU is available on users’ devices in late 2026?
No — it’s broadly available on modern devices but not universal; always feature-detect and provide a fallback.
5. For a 40-point line chart, which technology and why?
SVG: tiny, accessible, styleable, retained.
Exercises
Section titled “Exercises”Warm-up 1. Choose the stack. (a) An animated logo; (b) a 3D product viewer; (c) a heatmap of 2 million cells updated live; (d) a frosted header over a static photo.
Solution
(a) CSS/SVG; (b) WebGL via Three.js (WebGPU optional); (c) WebGPU compute with WebGL fallback, or WebGL with texture-based aggregation; (d) CSS with a pre-blurred backdrop or modest backdrop-filter.
Warm-up 2. Workgroups. You have 100,000 particles and @workgroup_size(64). How many workgroups do you dispatch?
Solution
ceil(100000 / 64) = 1,563 — and the shader must bounds-check the last partial group.
Warm-up 3. Fallback chain. Write the detection order for a feature that prefers WebGPU.
Solution
navigator.gpu → requestAdapter() non-null → requestDevice() succeeds → else WebGL2 context → else WebGL1 (or skip) → else static image.
Lab 4. WebGPU particles for Lumen. Add a WebGPU particle header to Lumen as a progressive enhancement over Chapter 20’s WebGL hero: compute-driven particles, paused off-screen, disabled under reduced motion.
Expected outcome
On WebGPU-capable browsers, smooth particles with near-zero main-thread cost; elsewhere, the WebGL hero or static image.
Lab 5. Port the triangle. Port Chapter 20’s raw WebGL triangle to WebGPU. Compare the per-frame code and its main-thread time.
Expected outcome
More setup, a smaller per-frame recording; both trivially fast for one triangle — try the 5,000-draw version to see CPU differences.
Lab 6. Same chart, three ways. Render a 20,000-point scatter plot in SVG, Canvas 2D and WebGL. Measure initial render time, interaction (hover) cost and memory.
Expected outcome
SVG struggles (20,000 DOM nodes); Canvas handles it; WebGL handles it with room to spare. Add an accessible summary for all three.
Staff 7. Graphics decision record. Write the decision record for the author’s lens effects: technology, budget, fallbacks, accessibility equivalent, and how you’ll verify.
Model outline
One shared WebGL2 context; ≤ N live surfaces; ≤ 4 ms GPU and ≤ 2 ms CPU per frame on reference devices; static tier for weak/no-GPU/reduced motion/reduced transparency; DOM content unaffected for a11y; verified with Chapter 16’s audit re-run and real-device traces.
Staff 8. “Should we rewrite in WebGPU?” A teammate proposes rewriting the WebGL visualization in WebGPU. Write the evaluation.
Model answer
Identify the current bottleneck (CPU draw overhead vs GPU fill vs compute needs). If CPU-bound on draw calls, instancing in WebGL2 may fix it cheaply; if compute is the need, WebGPU compute is compelling. Account for fallback maintenance, team skills and device coverage. Recommend a measured spike, not a rewrite.