home/ atoms/ webgpu-typed-array-vertex-data

Vertex data passed to WebGPU must live in a JavaScript TypedArray matching the expected GPU numeric format

WebGPU buffers hold raw GPU-side memory. To copy data into them from JavaScript, you use TypedArrays. The most common is Float32Array for floating-point vertex coordinates (matching float32x2 vertex format). The right TypedArray type must match the format declared in the vertex buffer layout. TypedArrays expose .byteLength for sizing buffers correctly. They are also used for uniforms and cell state (Uint32Array). Plain JavaScript arrays cannot be passed to WebGPU because the GPU requires memory-layout guarantees they do not provide.

Examples

const vertices = new Float32Array([
  -0.8,-0.8,  0.8,-0.8,  0.8,0.8,
  -0.8,-0.8,  0.8, 0.8, -0.8,0.8,
]);
// vertices.byteLength === 48 (12 floats × 4 bytes)

Assessment

Why does device.createBuffer({ size: vertices.byteLength }) use .byteLength rather than .length? What goes wrong if you pass a plain JS array instead of a TypedArray?

“TypedArrays are great for sending data back and forth with APIs that are sensitive to memory layout”
corpus · your-first-webgpu-app-google-codelab · chunk 4