概述WebGPU 提供现代图形与计算能力。流程包括请求适配器与设备、配置画布上下文、创建着色器与渲染管线,最后通过命令编码器提交绘制或计算工作。用法/示例const adapter = await navigator.gpu.requestAdapter() const device = await adapter.requestDevice() const canvas = document.querySelector('canvas') const ctx = canvas.getContext('webgpu') const format = navigator.gpu.getPreferredCanvasFormat() ctx.configure({ device, format }) const shader = ` @vertex fn vs_main(@builtin(vertex_index) i : u32) -> @builtin(position) vec4<f32> { var p = array<vec2<f32>, 3>(vec2<f32>(0.0, 0.5), vec2<f32>(-0.5, -0.5), vec2<f32>(0.5, -0.5)); return vec4<f32>(p[i], 0.0, 1.0); } @fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(0.31, 0.27, 0.90, 1.0); } ` const module = device.createShaderModule({ code: shader }) const pipeline = device.createRenderPipeline({ layout: 'auto', vertex: { module, entryPoint: 'vs_main' }, fragment: { module, entryPoint: 'fs_main', targets: [{ format }] } }) const encoder = device.createCommandEncoder() const pass = encoder.beginRenderPass({ colorAttachments: [{ view: ctx.getCurrentTexture().createView(), loadOp: 'clear', storeOp: 'store', clearValue: { r: 1, g: 1, b: 1, a: 1 } }] }) pass.setPipeline(pipeline) pass.draw(3) pass.end() device.queue.submit([encoder.finish()]) 工程建议检测支持性并提供回退(WebGL 或静态渲染)。对着色器与缓冲进行复用与资源生命周期管理,避免频繁创建。使用性能分析工具与标记定位瓶颈,合理划分渲染/计算工作。参考与验证MDN:WebGPU API — https://developer.mozilla.org/docs/Web/API/WebGPU_APIweb.dev:WebGPU — https://web.dev/articles/webgpuW3C GPUWeb — https://www.w3.org/community/gpuweb/

发表评论 取消回复