Skip to content

Vertex Buffers

This example stops hard-coding the triangle in the shader and reads it from a vertex buffer. Each vertex is five floats: x, y, r, g, and b. The full explanation is in Buffers.

Colored vertices

const vertices = new Float32Array([
0.0, 0.5, 1.0, 0.25, 0.2,
-0.5, -0.5, 0.2, 0.85, 0.35,
0.5, -0.5, 0.25, 0.45, 1.0,
]);
const vertexBuffer = device.createBuffer({
size: vertices.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(vertexBuffer, 0, vertices);
const pipeline = device.createRenderPipeline({
layout: "auto",
vertex: {
module: shaderModule,
entryPoint: "vs_main",
buffers: [
{
arrayStride: 20,
attributes: [
{ shaderLocation: 0, offset: 0, format: "float32x2" },
{ shaderLocation: 1, offset: 8, format: "float32x3" },
],
},
],
},
fragment: {
module: shaderModule,
entryPoint: "fs_main",
targets: [{ format: canvasFormat }],
},
primitive: { topology: "triangle-list" },
});
pass.setPipeline(pipeline);
pass.setVertexBuffer(0, vertexBuffer);
pass.draw(3);

The shader receives a vec2f position at @location(0) and a vec3f color at @location(1).