files/en-us/web/api/gpuqueue/writebuffer/index.md
{{APIRef("WebGPU API")}}{{SecureContext_Header}}{{AvailableInWorkers}}
The writeBuffer() method of the
{{domxref("GPUQueue")}} interface writes a provided data source into a given {{domxref("GPUBuffer")}}.
This is a convenience function, which provides an alternative to setting buffer data via buffer mapping and buffer-to-buffer copies. It lets the user agent determine the most efficient way to copy the data over.
writeBuffer(buffer, bufferOffset, data, dataOffset, size)
buffer
bufferOffset
data
dataOffset {{optional_inline}}
data is a {{jsxref("TypedArray")}}, and a number of bytes if not. If omitted, dataOffset defaults to 0.size {{optional_inline}}
data to buffer. This value is a number of elements if data is a {{jsxref("TypedArray")}}, and a number of bytes if not. If omitted, size will be equal to the overall size of data, minus dataOffset.None ({{jsxref("Undefined")}}).
OperationError {{domxref("DOMException")}}
OperationError if the following criteria are not met:
data is equal to or greater than 0.dataOffset is equal to or smaller than the size of data.data (when converted to bytes, in the case of TypedArrays) is a multiple of 4.The following criteria must be met when calling writeBuffer(), otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPUQueue")}} becomes invalid:
buffer is available for use, i.e., not unavailable (GPUBuffers are unavailable if they are currently {{domxref("GPUBuffer.mapAsync", "mapped", "", "nocode")}}) or destroyed (with the {{domxref("GPUBuffer.destroy()")}} method).buffer's {{domxref("GPUBuffer.usage")}} includes the GPUBufferUsage.COPY_DST flag.bufferOffset, when converted to bytes, is a multiple of 4.data - dataOffset + bufferOffset, when converted to bytes, is equal to or less than the buffer's {{domxref("GPUBuffer.size")}}.In our basic render demo, we define some vertex data in a {{jsxref("Float32Array")}} that we'll use to draw a triangle:
const vertices = new Float32Array([
0.0, 0.6, 0, 1, 1, 0, 0, 1, -0.5, -0.6, 0, 1, 0, 1, 0, 1, 0.5, -0.6, 0, 1, 0,
0, 1, 1,
]);
To use this data in a render pipeline, we need to put it into a {{domxref("GPUBuffer")}}. First we'll create the buffer:
const vertexBuffer = device.createBuffer({
size: vertices.byteLength, // make it big enough to store vertices in
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
});
To get the data into the buffer we can use writeBuffer():
device.queue.writeBuffer(vertexBuffer, 0, vertices, 0, vertices.length);
{{Specifications}}
{{Compat}}