背景与价值WebGPU 提供现代图形与并行计算能力,显著提升渲染与数据处理性能。结合回退策略保证在不支持的设备上仍可用。设备与上下文async function initWebGPU(canvas: HTMLCanvasElement) {

if (!('gpu' in navigator)) return { ok: false, reason: 'unsupported' };

const adapter = await (navigator as any).gpu.requestAdapter();

const device = await adapter.requestDevice();

const ctx = (canvas.getContext('webgpu') as GPUCanvasContext);

const format = (navigator as any).gpu.getPreferredCanvasFormat();

ctx.configure({ device, format, alphaMode: 'opaque' });

return { ok: true, device, ctx, format };

}

渲染管线(三角形)const shader = /* wgsl */ `

@vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {

var pos = array<vec2<f32>, 3>(

vec2<f32>(0.0, 0.6),

vec2<f32>(-0.6, -0.6),

vec2<f32>(0.6, -0.6)

);

let p = pos[vi];

return vec4<f32>(p, 0.0, 1.0);

}

@fragment fn fs_main() -> @location(0) vec4<f32> {

return vec4<f32>(0.1, 0.6, 0.9, 1.0);

}

`;

function renderTriangle(device: GPUDevice, ctx: GPUCanvasContext, format: GPUTextureFormat) {

const module = device.createShaderModule({ code: shader });

const pipeline = device.createRenderPipeline({

layout: 'auto',

vertex: { module, entryPoint: 'vs_main' },

fragment: { module, entryPoint: 'fs_main', targets: [{ format }] },

primitive: { topology: 'triangle-list' }

});

const encoder = device.createCommandEncoder();

const view = ctx.getCurrentTexture().createView();

const pass = encoder.beginRenderPass({ colorAttachments: [{ view, loadOp: 'clear', clearValue: { r: 0.02, g: 0.02, b: 0.02, a: 1 }, storeOp: 'store' }] });

pass.setPipeline(pipeline);

pass.draw(3);

pass.end();

device.queue.submit([encoder.finish()]);

}

计算着色器示例const computeWGSL = /* wgsl */ `

@group(0) @binding(0) var<storage, read_write> data: array<f32>;

@compute @workgroup_size(64)

fn main(@builtin(global_invocation_id) gid: vec3<u32>) {

let i = gid.x;

data[i] = data[i] * 2.0;

}

`;

async function runCompute(device: GPUDevice) {

const N = 1024;

const buf = device.createBuffer({ size: N * 4, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST });

const pipeline = device.createComputePipeline({ layout: 'auto', compute: { module: device.createShaderModule({ code: computeWGSL }), entryPoint: 'main' } });

const bind = device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer: buf } }] });

const encoder = device.createCommandEncoder();

const pass = encoder.beginComputePass();

pass.setPipeline(pipeline); pass.setBindGroup(0, bind); pass.dispatchWorkgroups(Math.ceil(N / 64)); pass.end();

device.queue.submit([encoder.finish()]);

}

回退到 WebGL2function fallbackWebGL2(canvas: HTMLCanvasElement) {

const gl = canvas.getContext('webgl2');

if (!gl) return { ok: false };

gl.clearColor(0.02, 0.02, 0.02, 1.0); gl.clear(gl.COLOR_BUFFER_BIT);

return { ok: true };

}

指标验证(Chrome 128/Edge 130)渲染帧率:静态场景稳定 ≥ 60fps(1080p)。计算吞吐:数组大小 1e6 的倍增任务较 JS 循环提升 2×–4×(设备差异)。回退稳定性:不支持 WebGPU 的设备仍能渲染基本内容,无崩溃。测试清单设备检测:WebGPU 支持与否路径均成功;异常有清晰提示。多尺寸画布:高 DPI 下配置格式正确,颜色输出稳定。计算正确性:随机数据写回结果与预期一致。应用场景数据可视化、图像处理、科学计算、游戏与高性能 UI 动效。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部