概述WebGPU 除渲染外还支持计算着色器,适合并行数据处理、图像滤波与物理模拟。通过 `ComputePipeline` 与 `StorageBuffer` 将数据送入 GPU 执行并读回。示例(简化)const adapter = await navigator.gpu.requestAdapter() const device = await adapter.requestDevice() const code = ` @group(0) @binding(0) var<storage, read_write> buf: array<u32>; @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) gid: vec3<u32>) { let i = gid.x; if (i < arrayLength(&buf)) { buf[i] = buf[i] + 1u } }` const module = device.createShaderModule({ code }) const pipeline = device.createComputePipeline({ layout: 'auto', compute: { module, entryPoint: 'main' } }) const data = new Uint32Array(1024) const buffer = device.createBuffer({ size: data.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC }) device.queue.writeBuffer(buffer, 0, data) const bind = device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer } }] }) const encoder = device.createCommandEncoder() const pass = encoder.beginComputePass(); pass.setPipeline(pipeline); pass.setBindGroup(0, bind); pass.dispatchWorkgroups(Math.ceil(data.length / 64)); pass.end() device.queue.submit([encoder.finish()]) 工程建议资源与同步:控制缓冲大小与同步;避免频繁读回导致性能瓶颈。功耗与平台:移动端注意功耗与温度;必要时降级到 CPU。兼容:不支持时回退到 WebGL2/CPU;检测设备与特性。参考与验证W3C WebGPU 规范:https://www.w3.org/TR/webgpu/MDN WebGPU 文档:https://developer.mozilla.org/docs/Web/API/WebGPU_APIweb.dev WebGPU 文章:https://web.dev/articles/webgpu

发表评论 取消回复