000: Hello GPU

2026-10-11

A dead simple WebGPU program: just clear a canvas to a colour. We ask the browser for an adapter (the physical GPU) and a device (a handle to it). Tell the canvas context to use that device. Then set up commands with an encoder, run them in a render pass that just clears the canvas texture, and submit it.

Moving Figures

No matching items
Show code
{
  if (!navigator.gpu) throw new Error("WebGPU is not supported in this browser.");

  // 1. Canvas (640x480 buffer, scaled to fill the column)
  const canvas = DOM.canvas(640, 480);
  canvas.style.width = "100%";
  canvas.style.height = "auto";

  // 2. Adapter and device
  const adapter = await navigator.gpu.requestAdapter();
  const device = await adapter.requestDevice();

  // 3. Context
  const context = canvas.getContext("webgpu");
  const format = navigator.gpu.getPreferredCanvasFormat();
  context.configure({ device, format });

  // 4. Record: a render pass that clears to the site's dark background (#1a1a1a)
  const encoder = device.createCommandEncoder();
  const pass = encoder.beginRenderPass({
    colorAttachments: [
      {
        view: context.getCurrentTexture().createView(),
        clearValue: { r: 0.102, g: 0.102, b: 0.102, a: 1.0 }, // #1a1a1a
        loadOp: "clear",
        storeOp: "store",
      },
    ],
  });
  pass.end();

  // 5. Submit
  device.queue.submit([encoder.finish()]);

  yield canvas;
}