引言
WebGPU 是继 WebGL 之后的下一代 Web 图形 API,它提供了更底层的 GPU 控制能力,能够实现更高性能的渲染和计算操作。作为 W3C 正在制定的标准,WebGPU 已经在 Chrome 113+ 和 Edge 中得到支持。
WebGPU 的核心优势:更接近底层 GPU API(如 Vulkan、Metal、DirectX 12),减少抽象开销,释放硬件真正性能。
WebGL vs WebGPU 对比
| 特性 | WebGL | WebGPU |
|---|---|---|
| 底层 API | OpenGL ES 2.0/3.0 | Vulkan/Metal/DX12 |
| 状态管理 | 全局状态机 | 命令缓冲区 |
| 着色器语言 | GLSL | WGSL |
| 计算能力 | WebGL 2.0 有限支持 | 原生计算着色器 |
| 性能开销 | 较高抽象层 | 接近原生性能 |
核心概念
1. 设备(GPUDevice)
GPUDevice 是 WebGPU 的核心对象,代表与 GPU 的连接。所有资源创建和命令提交都通过设备进行。
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
2. 命令缓冲区(GPUCommandBuffer)
WebGPU 采用命令缓冲区模式,先录制命令,再一次性提交执行,减少 API 调用开销。
const commandEncoder = device.createCommandEncoder();
// 录制渲染命令...
const commandBuffer = commandEncoder.finish();
device.queue.submit([commandBuffer]);
3. 管线(GPURenderPipeline)
管线是 WebGPU 的核心配置单元,包含着色器、顶点格式、混合模式等所有渲染状态的预配置。
const pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: { module: shaderModule, entryPoint: 'vertexMain' },
fragment: { module: shaderModule, entryPoint: 'fragmentMain', targets: [{ format: 'bgra8unorm' }] }
});
WGSL 着色器语言
WebGPU 使用 WGSL(WebGPU Shading Language)作为着色器语言,语法类似 Rust,比 GLSL 更现代化。
@vertex
fn vertexMain(@location(0) pos: vec2<f32>) -> @builtin(position) vec4<f32> {
return vec4<f32>(pos, 0.0, 1.0);
}
@fragment
fn fragmentMain() -> @location(0) vec4<f32> {
return vec4<f32>(0.0, 0.94, 1.0, 1.0); // 霓虹青色
}
实践示例:绘制三角形
下面是一个完整的 WebGPU 初始化和三角形渲染流程:
// 1. 初始化
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
const canvas = document.querySelector('canvas');
const context = canvas.getContext('webgpu');
context.configure({ device, format: 'bgra8unorm' });
// 2. 创建着色器
const shaderCode = `
@vertex fn vs(@location(0) p: vec2<f32>) -> @builtin(position) vec4<f32> {
return vec4<f32>(p, 0.0, 1.0);
}
@fragment fn fs() -> @location(0) vec4<f32> {
return vec4<f32>(1.0, 0.0, 0.94, 1.0);
}
`;
const shaderModule = device.createShaderModule({ code: shaderCode });
// 3. 创建管线
const pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: { module: shaderModule, entryPoint: 'vs' },
fragment: { module: shaderModule, entryPoint: 'fs', targets: [{ format: 'bgra8unorm' }] }
});
// 4. 渲染循环
function render() {
const encoder = device.createCommandEncoder();
const pass = encoder.beginRenderPass({
colorAttachments: [{
view: context.getCurrentTexture().createView(),
loadOp: 'clear', clearValue: { r: 0.02, g: 0.02, b: 0.05, a: 1 },
storeOp: 'store'
}]
});
pass.setPipeline(pipeline);
pass.draw(3);
pass.end();
device.queue.submit([encoder.finish()]);
}
总结
WebGPU 代表了 Web 图形技术的未来方向,它释放了现代 GPU 的真正性能潜力。虽然目前浏览器支持还在推进中,但掌握 WebGPU 将是前端图形开发者的核心竞争力。
建议的学习路径:先理解 GPU 编程基础概念 → 学习 WGSL 语法 → 实践简单渲染示例 → 探索计算着色器 → 构建完整应用。