The First Triangle

Drawing a single triangle in WebGPU requires more setup than WebGL, but establishes a robust pipeline that scales predictably.

1. Initialization

Before issuing commands to the GPU, we need to request an adapter and a device.

const adapter = await navigator.gpu.requestAdapter();
if (!adapter) throw new Error("No WebGPU adapter found.");
const device = await adapter.requestDevice();

Context Configuration Calculator

Actual Buffer Size: x px

Memory footprint (RGBA8Unorm): MB

2. The Shader

WebGPU uses WGSL. We embed the positions directly in the vertex shader for this simple example.

@vertex
fn main(@builtin(vertex_index) VertexIndex : u32) -> @builtin(position) vec4<f32> {
  var pos = array<vec2<f32>, 3>(
    vec2<f32>(0.0, 0.5),
    vec2<f32>(-0.5, -0.5),
    vec2<f32>(0.5, -0.5)
  );
  return vec4<f32>(pos[VertexIndex], 0.0, 1.0);
}

@fragment
fn main() -> @location(0) vec4<f32> {
  return vec4<f32>(1.0, 0.0, 0.0, 1.0);
}