大网数据广告活动
Web 标准与前端开发

GPUBuffer

· 52CE 我爱测

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.

WebGPU API

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 GPUDevice.createBuffer() method.

Instance properties

  • GPUBuffer.label
    • : A string providing a label that can be used to identify the object, for example in GPUError messages or console warnings.
  • GPUBuffer.mapState
    • : An enumerated value representing the mapped state of the GPUBuffer.
  • GPUBuffer.size
    • : A number representing the length of the GPUBuffer's memory allocation, in bytes.
  • GPUBuffer.usage
    • : The bitwise flags representing the allowed usages of the GPUBuffer.

Instance methods

  • GPUBuffer.destroy
    • : Destroys the GPUBuffer.
  • GPUBuffer.getMappedRange
    • : Returns an ArrayBuffer containing the mapped contents of the GPUBuffer in the specified range.
  • GPUBuffer.mapAsync
    • : Maps the specified range of the GPUBuffer. Returns a Promise that resolves when the GPUBuffer's content is ready to be accessed with GPUBuffer.getMappedRange().
  • GPUBuffer.unmap
    • : Unmaps the mapped range of the GPUBuffer, making its contents available for use by the GPU again.

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:

  • GPUBuffer.mapAsync() is used to map the GPUBuffer for reading.
  • GPUBuffer.getMappedRange() is used to return an ArrayBuffer containing the GPUBuffer's contents.
  • GPUBuffer.unmap() is used to unmap the GPUBuffer again, 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

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。