Source: ViewEdit

Draw a triangle and run a compute shader

In this tutorial, you will run two small GPU programs inside a single local HTML file: first a WebGL 2 draw call that paints a green triangle on a <canvas>, and second a WebGPU compute shader written in WGSL that adds 1 to every integer in a 128-element array. Both programs execute on your graphics card without installing CUDA, ROCm, or the Vulkan SDK, and seeing them side by side makes the boundary between rendering and compute unmistakable — different contexts, different shading languages, and different kinds of output.

This lesson is the hands-on companion to Graphics programming and GPU compute. If you want the full map of GPU APIs and translators first, start with GPU programming.

Prerequisites

You only need a current desktop browser (Chrome, Edge, or a Firefox build exposing navigator.gpu) and a text editor. WebGL 2 has shipped in desktop browsers for years; WebGPU is available in current desktop Chrome, Edge, and Firefox builds that enable navigator.gpu. There is no build step and no npm install — opening the HTML file directly from disk (file://) or from any local static server is enough.

If your browser does not expose navigator.gpu, the page still draws the WebGL 2 triangle and prints a message saying WebGPU is unavailable. That partial run is informative on its own: drawing and compute enter the browser through separate doors.

Build and open the page

Save the following file as triangle-and-compute.html and open it in your browser.

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Draw a triangle and run a compute shader</title>
<body>
<canvas id="c" width="320" height="180"></canvas>
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const canvas = document.getElementById("c");

// Part 1: Graphics programming -- draw one triangle with WebGL 2.
const gl = canvas.getContext("webgl2");
if (!gl) {
  out.textContent = "This browser has no WebGL 2 context.";
} else {
  const vs = `#version 300 es
void main() {
  vec2 p[3] = vec2[3](vec2(-0.6, -0.5), vec2(0.6, -0.5), vec2(0.0, 0.6));
  gl_Position = vec4(p[gl_VertexID], 0.0, 1.0);
}`;
  const fs = `#version 300 es
precision mediump float;
out vec4 color;
void main() { color = vec4(0.20, 0.55, 0.35, 1.0); }`;

  function compileShader(type, source) {
    const s = gl.createShader(type);
    gl.shaderSource(s, source);
    gl.compileShader(s);
    if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
      throw new Error(gl.getShaderInfoLog(s) || "shader compile failed");
    }
    return s;
  }

  const program = gl.createProgram();
  gl.attachShader(program, compileShader(gl.VERTEX_SHADER, vs));
  gl.attachShader(program, compileShader(gl.FRAGMENT_SHADER, fs));
  gl.linkProgram(program);
  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
    throw new Error(gl.getProgramInfoLog(program) || "program link failed");
  }

  gl.viewport(0, 0, canvas.width, canvas.height);
  gl.clearColor(0.95, 0.94, 0.90, 1);
  gl.clear(gl.COLOR_BUFFER_BIT);
  gl.useProgram(program);
  gl.drawArrays(gl.TRIANGLES, 0, 3);
}

// Part 2: GPU compute -- add 1 to 128 integers with a WebGPU compute shader.
async function addOneOnGpu() {
  if (!navigator.gpu) {
    return "WebGPU is unavailable. The triangle ran on WebGL 2 only.";
  }
  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    return "WebGPU found no usable GPU adapter.";
  }
  const device = await adapter.requestDevice();

  const module = device.createShaderModule({
    code: `
      @group(0) @binding(0) var<storage, read_write> data: array<u32>;
      @compute @workgroup_size(64)
      fn main(@builtin(global_invocation_id) id: vec3<u32>) {
        let i = id.x;
        if (i >= arrayLength(&data)) { return; }
        data[i] = data[i] + 1u;
      }
    `,
  });

  const n = 128;
  const cpu = new Uint32Array(n);
  for (let i = 0; i < n; i++) cpu[i] = i;

  const storage = device.createBuffer({
    size: cpu.byteLength,
    usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
  });
  device.queue.writeBuffer(storage, 0, cpu);

  const pipeline = device.createComputePipeline({
    layout: "auto",
    compute: { module, entryPoint: "main" },
  });
  const bindGroup = device.createBindGroup({
    layout: pipeline.getBindGroupLayout(0),
    entries: [{ binding: 0, resource: { buffer: storage } }],
  });

  const encoder = device.createCommandEncoder();
  const pass = encoder.beginComputePass();
  pass.setPipeline(pipeline);
  pass.setBindGroup(0, bindGroup);
  pass.dispatchWorkgroups(Math.ceil(n / 64));
  pass.end();

  const readback = device.createBuffer({
    size: cpu.byteLength,
    usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  });
  encoder.copyBufferToBuffer(storage, 0, readback, 0, cpu.byteLength);
  device.queue.submit([encoder.finish()]);

  await readback.mapAsync(GPUMapMode.READ);
  const result = new Uint32Array(readback.getMappedRange().slice(0));
  readback.unmap();

  const ok = result[0] === 1 && result[1] === 2 && result[127] === 128;
  return ok
    ? "WebGPU compute wrote " + result[0] + " " + result[1] + " ... " + result[127]
    : "Unexpected result: " + result[0] + " " + result[1];
}

addOneOnGpu()
  .then((line) => {
    out.textContent = (out.textContent ? out.textContent + "\n" : "") + line;
  })
  .catch((error) => {
    out.textContent = (out.textContent ? out.textContent + "\n" : "") + String(error);
  });
</script>
</body>
</html>

When you open the file, you should see a green triangle centered on a warm-gray rectangle, followed by the text WebGPU compute wrote 1 2 …​ 128. The CPU initialized the array to 0, 1, …​, 127, uploaded it to the GPU, and every parallel lane incremented its own element by one.

Walking through Part 1: the WebGL 2 draw call

Calling canvas.getContext("webgl2") asks the browser for an OpenGL ES 3.0 rendering context bound to that <canvas>. The vertex shader runs three times because gl.drawArrays(gl.TRIANGLES, 0, 3) requests three vertices; instead of loading a vertex buffer, the shader uses the built-in gl_VertexID (0, 1, and 2) to pick three clip-space coordinates and return them through gl_Position. Fixed-function rasterization hardware turns those three points into a triangle on screen and calls the fragment shader once per covered pixel, painting every fragment the same green RGBA color.

Notice what this context cannot do: because WebGL 2 stops at OpenGL ES 3.0, there is no compute pipeline and no general workgroup dispatch. Also notice what happened underneath the browser: on Windows, ANGLE almost certainly translated those GLSL ES shaders and WebGL calls into Direct3D 11 (or Metal on macOS) before the vendor driver ever saw them, even though your JavaScript never mentioned Direct3D or Metal. See Graphics programming for the full rendering pipeline and WebGPU’s own render path.

Walking through Part 2: the WebGPU compute pass

Calling navigator.gpu.requestAdapter() and adapter.requestDevice() opens a WebGPU device — completely independent of the WebGL 2 context above. The WGSL shader declares a read-write storage buffer (var<storage, read_write> data: array<u32>) and marks main as a @compute entry point with @workgroup_size(64).

Because n = 128, pass.dispatchWorkgroups(Math.ceil(n / 64)) launches 2 workgroups of 64 invocations each, giving 128 parallel lanes. Each lane reads its global index (id.x), guards against running past the end of the array, and writes data[i] + 1u.

Pay special attention to the two buffers:

  • storage holds the array in GPU-managed memory (STORAGE | COPY_SRC | COPY_DST) so the compute shader can read and write it at full device speed. device.queue.writeBuffer uploads the initial Uint32Array from JavaScript.

  • readback is a separate staging buffer (COPY_DST | MAP_READ). GPU buffers are not CPU mmap memory; WebGPU does not let you map a live storage buffer directly into JavaScript, so the command encoder copies storage into readback after the compute pass finishes, submits the work, and awaits readback.mapAsync(GPUMapMode.READ).

Underneath the browser, Chrome’s Dawn or Firefox’s wgpu compiled your WGSL shader and submitted that compute pass to Direct3D 12, Metal, or Vulkan. You just ran the exact same parallel pattern as a CUDA kernel without installing a native compiler. Read GPU compute to see this exact add-one kernel compared line for line across CUDA, HIP, Vulkan, and WebGPU.

Next steps