files/en-us/web/api/gpucommandencoder/copybuffertobuffer/index.md
{{APIRef("WebGPU API")}}{{SecureContext_Header}}
The copyBufferToBuffer() method of the
{{domxref("GPUCommandEncoder")}} interface encodes a command that copies data from one {{domxref("GPUBuffer")}} to another.
copyBufferToBuffer(source, destination)
copyBufferToBuffer(source, destination, size)
copyBufferToBuffer(source, sourceOffset, destination, destinationOffset, size)
source
sourceOffset {{optional_inline}}
source to begin copying from.destination
destinationOffset {{optional_inline}}
destination to begin copying to.size {{optional_inline}}
[!NOTE] The
sourceOffsetanddestinationOffsetcan be omitted if you are copying part of the source buffer at a0offset in both the source and destination buffers. ThesourceOffset,destinationOffset, andsizecan be omitted if you are copying the entire source buffer to the destination buffer.
None ({{jsxref("Undefined")}}).
The following criteria must be met when calling copyBufferToBuffer(), otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPUCommandEncoder")}} becomes invalid:
source's {{domxref("GPUBuffer.usage")}} includes the GPUBufferUsage.COPY_SRC flag.destination's {{domxref("GPUBuffer.usage")}} includes the GPUBufferUsage.COPY_DST flag.size, sourceOffset, and destinationOffset are all multiples of 4.source's {{domxref("GPUBuffer.size")}} is greater than or equal to sourceOffset + size.destination's {{domxref("GPUBuffer.size")}} is greater than or equal to destinationOffset + size.source and destination are different {{domxref("GPUBuffer")}}s (you can't copy from and to the same buffer).In our basic compute demo, we use copyBufferToBuffer() to copy the contents of our outputBuffer to the stagingBuffer.
// …
// Create an output buffer to read GPU calculations to, and a staging buffer to be mapped for JavaScript access
const outputBuffer = device.createBuffer({
size: BUFFER_SIZE,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
});
const stagingBuffer = device.createBuffer({
size: BUFFER_SIZE,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
});
// …
// Create GPUCommandEncoder to encode commands to issue to the GPU
const commandEncoder = device.createCommandEncoder();
// …
// Copy output buffer to staging buffer
commandEncoder.copyBufferToBuffer(
outputBuffer,
0, // Source offset
stagingBuffer,
0, // Destination offset
BUFFER_SIZE,
);
// Since we are copying the entire buffer, this can be shortened to
// commandEncoder.copyBufferToBuffer(outputBuffer, stagingBuffer);
// …
{{Specifications}}
{{Compat}}