GPUDevice: createBuffer() method
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
Secure context: This feature is available only insecure contexts (HTTPS), in some or allsupporting browsers.
Note: This feature is available inWeb Workers.
ThecreateBuffer() method of theGPUDevice interface creates aGPUBuffer in which to store raw data to use in GPU operations.
In this article
Syntax
createBuffer(descriptor)Parameters
descriptorAn object containing the following properties:
labelOptionalA string providing a label that can be used to identify the object, for example in
GPUErrormessages or console warnings.mappedAtCreationOptionalA boolean. If set to
true, the buffer will be mapped upon creation, meaning that you can set the values inside the buffer immediately by callingGPUBuffer.getMappedRange(). The default value isfalse.Note that it is valid to set
mappedAtCreation: trueso you can set the buffer's initial data, even if theGPUBufferUsage.MAP_READorGPUBufferUsage.MAP_WRITEusage flags are not set.sizeA number representing the size of the buffer, in bytes. If
mappedAtCreationis set totrue, this must be a multiple of4.usageThebitwise flags representing the allowed usages for the
GPUBuffer. The possible values are in theGPUBuffer.usagevalue table.Note that multiple possible usages can be specified by separating values withbitwise OR, for example:
GPUBufferUsage.COPY_SRC | GPUBufferUsage.MAP_WRITE.
Return value
AGPUBuffer object instance.
Exceptions
RangeErrorDOMExceptionThrown if
mappedAtCreationis set totrue, and the specifiedsizeis not a multiple of4.
Validation
The following criteria must be met when callingcreateBuffer(), otherwise aGPUValidationError is generated and an invalidGPUBuffer object is returned:
- A valid
usageis specified. GPUBufferUsage.MAP_READis specified, and no additional flags are specified other thanGPUBufferUsage.COPY_DST.GPUBufferUsage.MAP_WRITEis specified, and no additional flags are specified other thanGPUBufferUsage.COPY_SRC.
Note:If the buffer allocation fails without any specific side-effects, aGPUOutOfMemoryError object is generated.
Examples
In ourbasic 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,});Specifications
| Specification |
|---|
| WebGPU> # dom-gpudevice-createbuffer> |
Browser compatibility
See also
- TheWebGPU API