Skip to content

Instantly share code, notes, and snippets.

@greggman
Created August 28, 2025 21:23
Show Gist options
  • Save greggman/41fd862cb4e9cee690a76858279019fb to your computer and use it in GitHub Desktop.
Save greggman/41fd862cb4e9cee690a76858279019fb to your computer and use it in GitHub Desktop.
WebGPU: Hello Triangle Compute Shader
/*bug-in-github-api-content-can-not-be-empty*/
<canvas></canvas>
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
device.addEventListener('uncapturederror', e => console.log(e.error.message));
const module = device.createShaderModule({
code: `
@group(0) @binding(0) var tex: texture_storage_2d<rgba8unorm, write>;
@compute @workgroup_size(1) fn cs(@builtin(global_invocation_id) pos: vec3u) {
let half = textureDimensions(tex).x / 2;
var color = vec4f(1, 0, 0, 1);
if (abs(i32(pos.x - half)) > i32(pos.y)) {
color = vec4f(0, 0, 1, 1);
}
textureStore(tex, pos.xy, color);
}
`,
});
const pipeline = device.createComputePipeline({ layout: 'auto', compute: { module } });
const canvas = document.querySelector('canvas');
const context = canvas.getContext('webgpu');
context.configure({
device,
format: 'rgba8unorm',
usage: GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.TEXTURE_BINDING,
});
const texture = context.getCurrentTexture();
const bindGroup = device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: texture.createView() },
],
});
const encoder = device.createCommandEncoder();
const pass = encoder.beginComputePass();
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindGroup);
pass.dispatchWorkgroups(texture.width, texture.height);
pass.end();
device.queue.submit([encoder.finish()]);
{"name":"WebGPU: Hello Triangle Compute Shader","settings":{},"filenames":["index.html","index.css","index.js"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment