web api interface
GPUBuffer
Secure contextAvailable in workers
The GPUBuffer interface of the WebGPU API represents a block of memory that can be used to store raw data to use in GPU operations.
A GPUBuffer object instance is created using the createBuffer() method.
Instance properties
label- : A string providing a label that can be used to identify the object, for example in
GPUErrormessages or console warnings.
- : A string providing a label that can be used to identify the object, for example in
mapStateRead only- : An enumerated value representing the mapped state of the
GPUBuffer.
- : An enumerated value representing the mapped state of the
sizeRead only- : A number representing the length of the
GPUBuffer’s memory allocation, in bytes.
- : A number representing the length of the
usageRead only- : The bitwise flags representing the allowed usages of the
GPUBuffer.
- : The bitwise flags representing the allowed usages of the
Instance methods
destroy()- : Destroys the
GPUBuffer.
- : Destroys the
getMappedRange()- : Returns an
ArrayBuffercontaining the mapped contents of theGPUBufferin the specified range.
- : Returns an
mapAsync()- : Maps the specified range of the
GPUBuffer. Returns aPromisethat resolves when theGPUBuffer’s content is ready to be accessed withgetMappedRange().
- : Maps the specified range of the
unmap()- : Unmaps the mapped range of the
GPUBuffer, making its contents available for use by the GPU again.
- : Unmaps the mapped range of the
Examples
In our basic compute demo, we create an output buffer to read GPU calculations to, and a staging buffer to be mapped for JavaScript access.
const output = 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,
});
Later on, once the stagingBuffer contains the results of the GPU computation, a combination of GPUBuffer methods are used to read the data back to JavaScript so that it can then be logged to the console:
mapAsync()is used to map theGPUBufferfor reading.getMappedRange()is used to return anArrayBuffercontaining theGPUBuffer’s contents.unmap()is used to unmap theGPUBufferagain, once we have read the content into JavaScript as needed.
// map staging buffer to read results back to JS
await stagingBuffer.mapAsync(
GPUMapMode.READ,
0, // Offset
BUFFER_SIZE, // Length
);
const copyArrayBuffer = stagingBuffer.getMappedRange(0, BUFFER_SIZE);
const data = copyArrayBuffer.slice(0);
stagingBuffer.unmap();
console.log(new Float32Array(data));
Specifications
SpecificationsStandards references are available on the canonical MDN page.
Browser compatibility
Browser compatibilityCompatibility data is available on the canonical MDN page.
See also
- The WebGPU API