WebGPU From Zero · Episode 01
Hello, WebGPU
Hello, WebGPU is Episode 01 of WebGPU From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
For twenty years the web could only talk to the GPU through WebGL — a 2007-era translation of an even older OpenGL ES, full of hidden global state, stringly-typed everything, and zero access to the compute hardware that powers modern graphics and ML. WebGPU is the reset. It is a brand-new, explicit, modern API that maps almost 1:1 onto Vulkan, Metal, and D3D12 — the same low-level interfaces native engines use. It does rendering and it does general-purpose compute, and it shipped in Chrome and Edge in 2023. The browser can finally drive the GPU like a native engine.
That's a big promise, so let's make it concrete and a little addictive. The demo below is an animated, controllable color gradient — drag your mouse over it, scrub the sliders, switch palettes. It looks like a toy. It is secretly your first GPU program: a fragment shader running once per pixel, sixty times a second, on silicon. The exact pipeline you write today — adapter, device, shader module, render pass, uniform buffer — is the same one that will push a million particles in Episode 07. Nothing gets thrown away. We're just adding zeros.
What you're looking at
One canvas, one rectangle of pixels, and a tiny program that decides the color of every one of those pixels independently, in parallel, on the GPU. There is no 3D scene, no mesh, no lighting — just "for each pixel, given its position and the current time, what color?" That function is a fragment shader, and the whole demo is six versions of it, from the most boring (a single flat color) to a glowing animated cosine palette that reacts to your mouse.
The badge at the bottom-left tells you which
backend you're on: WebGPU if your browser supports it (Chrome/Edge 113+),
or fallback (no WebGPU) if not — in which case the page quietly draws a
Canvas2D twin of the same gradient so nothing is ever black. We'll establish that
fallback-and-badge pattern here and reuse it in all 24 episodes. The
fps counter top-left should read 60.
Stage 1 — The device handshake
Before a single pixel, WebGPU makes you do a short, explicit dance to get a handle on the hardware. Three calls, in order:
navigator.gpu— the entry point. It exists only in browsers that support WebGPU; checking it is step zero of the fallback.requestAdapter()— asks the system for a physical GPU (you can hint'high-performance'to prefer the discrete card on a laptop). Returnsnullif none is usable.requestDevice()— opens a logical device on that adapter: your actual connection for creating buffers, shaders, and pipelines.
Then you configure the canvas's 'webgpu' context with that
device and a pixel format. Stage 1 proves all of this worked by doing the simplest
possible thing: it clears the canvas to a solid color that slowly cycles. No geometry,
no shader of our own — just the render pass's clearValue, animated. If you
see a breathing color, the handshake succeeded and the device is live.
Stage 2 — The fullscreen triangle
To run a fragment shader over the whole screen, you need something to
rasterize. The instinct is "draw a quad" — two triangles covering the canvas. But the
idiomatic trick is to draw one oversized triangle with vertices at
(-1,-1), (3,-1), (-1,3). That single triangle
pokes way outside the [-1,1] clip box; the GPU clips it to the screen, and
what survives is exactly the visible rectangle — with no vertex buffer at all.
We generate the three corners from @builtin(vertex_index) right inside the
shader and call draw(3).
Why a triangle instead of a quad? A quad has a seam down its diagonal where the two triangles meet, which can cause tiny shading artifacts and redundant work along that edge. One triangle has no seam, uses fewer vertices, and is the standard "fullscreen pass" primitive in every modern renderer. Stage 2 tints that triangle a flat color so you can confirm it really does cover every pixel.
Stage 3 — The UV gradient
Now the fragment shader earns its keep. Every fragment knows its own pixel position
via @builtin(position). Divide that by the canvas resolution (which we pass
in through a uniform buffer) and you get a normalized uv in
[0,1]×[0,1] — 0 at the left/top, 1 at the right/bottom. Feed
uv.x into red and uv.y into green and you get the canonical
"hello shader" image: a smooth red-to-green gradient. This is the moment the GPU is
doing per-pixel work that you wrote.
A subtle gotcha that bites everyone once:@builtin(position)in the fragment shader is in pixels (e.g.0…1920), not the[-1,1]clip space the vertex shader returned. That's why we divide by the resolution to normalize it. We make resolution a uniform so it tracks DPR and resizes.
Stage 4 — Animated waves
A still gradient is a picture; motion makes it a program. We add a
time field to the uniform buffer and bump it every frame from JavaScript
with queue.writeBuffer. Inside the shader, sin(uv.x * scale +
time) ripples the color across the screen. The speed slider
scales how fast time advances; the scale slider sets the
spatial frequency (how many waves fit across). This is the entire structure of a
Shadertoy: pixel position in, time uniform driving it, color out.
Stage 5 — The mouse uniform
Uniforms aren't just for time. We also pack the mouse position
(in pixels) into the same buffer and update it on pointermove. The shader
measures each pixel's distance to the mouse and brightens a soft ring around the cursor.
Move your pointer over the canvas — the light follows it. Nothing here is special to the
mouse; it's just another few bytes in the uniform buffer, which is exactly how you'll
feed simulation parameters, camera matrices, and physics constants to the GPU later.
Stage 6 — It's a fragment shader
The payoff. Same pipeline, but the color comes from Inigo Quilez's
cosine palette: a + b * cos(2π(c·t + d)), a four-vector
recipe that produces gorgeous smooth gradients with three cheap cos calls.
We drive t with the animated UV and the mouse, and the palette
dropdown swaps the a/b/c/d constants between sunset, ocean, magma, and mono.
Step back and notice: this lush, living image is nothing but a function from pixel
coordinate to color, evaluated a couple million times per frame on the GPU. That's
the whole magic of shaders, and you now own the machine that runs them.
The code
Four pieces make the whole thing. First, the init + graceful fallback — the part that
guarantees the page is never black and the badge is always honest. Note it
never throws: every failure path returns a
{ ok:false, reason } object the caller can act on.
// (a) Handshake + canvas configure, with graceful fallback — never throws.
async function initWebGPU(canvas) {
if (!('gpu' in navigator))
return { ok: false, reason: 'navigator.gpu missing — open in Chrome/Edge 113+' };
let adapter;
try { adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' }); }
catch (e) { return { ok: false, reason: 'requestAdapter failed: ' + e.message }; }
if (!adapter) return { ok: false, reason: 'no GPU adapter available' };
const device = await adapter.requestDevice();
device.lost.then(info => console.warn('WebGPU device lost:', info.message));
const context = canvas.getContext('webgpu');
const format = navigator.gpu.getPreferredCanvasFormat(); // bgra8unorm or rgba8unorm
context.configure({ device, format, alphaMode: 'premultiplied' });
return { ok: true, adapter, device, context, format };
}
// Wire it up: set the badge, and on failure fall back to a Canvas2D twin.
const gpu = await initWebGPU(canvas);
badge.textContent = gpu.ok ? 'WebGPU' : 'fallback (no WebGPU)';
if (!gpu.ok) { notice.textContent = gpu.reason; runCanvas2DFallback(canvas); return; }
Second, the vertex shader — the fullscreen-triangle trick. Three hard-coded clip-space
corners selected by vertex_index; no vertex buffer, no attributes.
// (b) WGSL — fullscreen triangle. draw(3) with no vertex buffer.
@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {
// One big triangle that overhangs the screen; the GPU clips it to the viewport.
var p = array<vec2f, 3>(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0));
return vec4f(p[i], 0.0, 1.0);
}
Third, the fragment shader and its Uniforms struct. This is the brain of
the demo: res, time, mouse, plus our slider/stage
values, all in one buffer. Watch the layout — it's padded to a multiple of 16 bytes on
purpose (see pitfalls).
// (c) WGSL — the Uniforms struct + the gradient fragment shader.
struct Uniforms {
res: vec2f, // canvas size in physical pixels
mouse: vec2f, // pointer position in pixels
time: f32,
speed: f32,
scale: f32,
stage: f32, // which of the 6 looks to show
palette: f32,
_pad: vec3f, // a vec3f aligns to 16 → rounds the struct up to 64 bytes
};
@group(0) @binding(0) var<uniform> u: Uniforms;
// Inigo Quilez cosine palette: a + b*cos(6.28318*(c*t + d))
fn pal(t: f32, a: vec3f, b: vec3f, c: vec3f, d: vec3f) -> vec3f {
return a + b * cos(6.28318 * (c * t + d));
}
@fragment fn fs(@builtin(position) frag: vec4f) -> @location(0) vec4f {
// frag.xy is in PIXELS — normalize by resolution to get uv in [0,1].
let uv = frag.xy / u.res;
let t = u.time * u.speed;
var col = vec3f(0.0);
if (u.stage < 2.5) { // stage 3: flat UV gradient
col = vec3f(uv, 0.5);
} else if (u.stage < 3.5) { // stage 4: animated waves
let w = 0.5 + 0.5 * sin(uv.x * u.scale * 6.0 + t * 2.0);
col = vec3f(w, uv.y, 1.0 - w);
} else if (u.stage < 4.5) { // stage 5: mouse spotlight
let m = u.mouse / u.res;
let glow = 0.12 / (0.04 + distance(uv, m));
col = vec3f(uv, 0.5) + glow * vec3f(1.0, 0.8, 0.5);
} else { // stage 6: cosine palette
let m = u.mouse / u.res;
let tt = length(uv - 0.5) * u.scale + t * 0.4 + (m.x - 0.5);
col = pal(tt, vec3f(0.5), vec3f(0.5), vec3f(1.0), vec3f(0.0, 0.33, 0.67));
}
return vec4f(col, 1.0);
}
Fourth, the per-frame loop: write the current uniforms into the buffer, open a render
pass, draw the triangle, submit. Stage 1's "clear to a color" lives here too — it just
sets clearValue and draws nothing.
// (d) Per frame: update the uniform buffer, then one render pass with draw(3).
function frame(now) {
const t = (now - start) / 1000;
// pack the Uniforms struct (must match the WGSL layout / size).
uniformData.set([canvas.width, canvas.height, mouseX, mouseY,
t, speed, scale, stage, palette]);
device.queue.writeBuffer(ubo, 0, uniformData);
const enc = device.createCommandEncoder();
const pass = enc.beginRenderPass({ colorAttachments: [{
view: context.getCurrentTexture().createView(),
clearValue: clearCol, // animated solid color for stage 1
loadOp: 'clear', storeOp: 'store' }] });
if (stage >= 1) { // stages 2-6 actually draw the triangle
pass.setPipeline(pipeline);
pass.setBindGroup(0, bind);
pass.draw(3);
}
pass.end();
device.queue.submit([enc.finish()]);
requestAnimationFrame(frame);
}
Common pitfalls
navigator.gpuis undefined. WebGPU ships in Chrome and Edge (113+) and recent Safari; it may be off in Firefox or behind a flag on Linux. Always feature-detect first and degrade — ourinitWebGPUreturns{ ok:false }and the page falls back to Canvas2D instead of crashing.- Forgetting
context.configure. You must call it with a format fromnavigator.gpu.getPreferredCanvasFormat()before the first frame, orgetCurrentTexture()has nothing to hand you. Don't hard-code'bgra8unorm'— let the API pick the platform-optimal format. - Canvas DPR sizing. The CSS size and the drawing-buffer size are
different things. Set
canvas.width = clientWidth * devicePixelRatio(and height) or your gradient is blurry on Retina/HiDPI. Reconfigure on resize. - Uniform buffer size & alignment. Uniform buffers have a
minimum binding size and must respect std140-ish rules: a
vec3faligns to 16 bytes, and the struct's total size rounds up to a multiple of 16. That's why ourUniformsends with explicit padding — a wrong stride gives garbage colors or a validation error at bind-group creation. @builtin(position)is in PIXELS in the fragment shader. It is not the[-1,1]clip space the vertex shader returned. Divide by the resolution uniform to get a[0,1]uv. Forgetting this is the classic "why is my gradient a single color in the corner" bug.
Exercises
- Add a second palette via a uniform. You already have a
palettefield. Add a fiftha/b/c/dset in the shader'sif-ladder (tryd = vec3f(0.0, 0.1, 0.2)for a green-purple look) and a matching<option>. Confirm switching it changes nothing else — that's the point of uniforms. - Make scale react to mouse distance. In stage 6, replace the
constant
u.scalewithu.scale * (1.0 + distance(uv, m) * 2.0). Now the palette compresses near the cursor and stretches at the edges — interactivity with one line and zero new plumbing. - Add a vignette. Multiply the final color by
1.0 - smoothstep(0.4, 0.9, length(uv - 0.5))to darken the corners. It's a one-liner that instantly makes any shader look more "designed." Bonus: animate the inner radius withtime.
What's next
Episode 02 — The Render Pipeline. We graduate from the no-vertex-buffer trick to real geometry: an actual vertex buffer with positions and per-vertex colors, a vertex layout, and a varying that the GPU interpolates across the triangle. The result is a spinning, smoothly color-blended shape — and the moment the "pipeline" stops being an abstraction and becomes data you control. Everything we built today (device, uniforms, render pass) carries straight over; we just add the geometry stage.