[WebGPU][WGSL] Sample to draw a single polygon
Minimum sample to draw a triangle on WebGPU + WGSL
by cx20
HTML
<canvas id="c" width="512" height="512"></canvas>
<script id="vs" type="x-shader/x-vertex">
struct VertexOutput {
@builtin(position) Position : vec4<f32>
}
@vertex
fn main(
@location(0) position : vec3<f32>
) -> VertexOutput {
var output : VertexOutput;
output.Position = vec4<f32>(position, 1.0);
return output;
}
</script>
<script id="fs" type="x-shader/x-fragment">
@fragment
fn main() -> @location(0) vec4<f32> {
return vec4<f32>(0.0, 0.0, 1.0, 1.0);
}
</script>
CSS
* {
margin: 0;
padding: 0;
border: 0;
overflow: hidden;
}
body {
background: #fff;
font: 30px sans-serif;
}
JavaScript
const vs = document.getElementById("vs").textContent;
const fs = document.getElementById("fs").textContent;
init();
async function init() {
const gpu = navigator["gpu"];
const adapter = await gpu.requestAdapter();
const device = await adapter.requestDevice();
const c = document.getElementById("c");
c.width = window.innerWidth;
c.height = window.innerHeight;
const ctx = c.getContext("webgpu");
const format = gpu.getPreferredCanvasFormat();
ctx.configure({
device: device,
format: format,
alphaMode: "opaque"
});
const pipeline = device.createRenderPipeline({
layout: "auto",
vertex: {
module: device.createShaderModule({
code: vs
}),
entryPoint: "main",
buffers: [
{
arrayStride: 3 * 4,
attributes: [
{
// position
shaderLocation: 0,
offset: 0,
format: "float32x3"
}
]
}
]
},
fragment: {
module: device.createShaderModule({
code: fs
}),
entryPoint: "main",
targets: [
{
format: format
}
]
},
primitive: {
topology: "triangle-list"
}
});
const positions = [
0.0, 0.5, 0.0, // v0
-0.5,-0.5, 0.0, // v1
0.5,-0.5, 0.0 // v2
];
let vertexBuffer = makeVertexBuffer(device, new Float32Array(positions));
const render = function () {
const commandEncoder = device.createCommandEncoder();
const textureView = ctx.getCurrentTexture().createView();
const renderPassDescriptor = {
colorAttachments: [{
view:...