顶点缓冲区
这个例子把三角形从“坐标写在着色器里”改成从顶点缓冲读取。每个顶点 5 个浮点数:x、y、r、g、b。讲解见缓冲区。
彩色顶点
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);着色器侧用 @location(0) 接收 vec2f 位置,用 @location(1) 接收 vec3f 颜色。