WebGPU hello world in 2024

Below is a Game of Life simulation. It uses WebGPU.

Here’s the essential JavaScript:

const canvas = document.getElementById("example-canvas");
if (!navigator.gpu) {
  throw new Error("WebGPU not supported on this browser.");
}
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) {
  throw new Error("No appropriate GPUAdapter found.");
}
const device = await adapter.requestDevice();
const context = canvas.getContext("webgpu");
if (!context) {
  throw new Error("Canvas context not found");
}
context.configure({
  device: device,
  format: navigator.gpu.getPreferredCanvasFormat(),
});
const encoder = device.createCommandEncoder();
const pass = encoder.beginRenderPass({
  colorAttachments: [
    {
      view: context.getCurrentTexture().createView(),
      loadOp: "clear",
      clearValue: { r: 1, g: 0, b: 1, a: 1 },
      storeOp: "store",
    },
  ],
});
pass.end();
device.queue.submit([encoder.finish()]);

This is derived from this tutorial.

Tagged #programming, #webgpu.

Similar posts

More by Jim

Want to build a fantastic product using LLMs? I work at Granola where we're building the future IDE for knowledge work. Come and work with us! Read more or get in touch!

This page copyright James Fisher 2024. Content is not associated with my employer. Found an error? Edit this page.