let canvas document createElement canvas document body appendChild canvas console log canvas canvas width canvas height 512 console log w canvas width h canvas height let wgsltxt struct vsout builtin position Position vec4 f32 location 0 p vec3 f32 stage vertex fn main vs builtin vertex index VertexIndex u32 vsout var pos array vec2 f32 3 vec2 f32 0 0 0 5 vec2 f32 0 5 0 5 vec2 f32 0 5 0 5 var ret vsout ret Position vec4 f32 pos VertexIndex 0 0 1 0 ret p vec3 f32 pos VertexIndex 0 0 return ret fn random st vec2 f32 f32 return fract sin dot st xy vec2 f32 12 9898 78 233 43758 5453123 stage fragment fn main fs location 0 p vec3 f32 location 0 vec4 f32 var r random p xy var g random p xy 2 0 var b random p xy 4 0 return vec4 f32 r g b 1 0 const gpu navigator gpu const adapter await gpu requestAdapter const device await adapter requestDevice context type gpupresent is deprecated Use webgpu instead const ctx canvas getContext gpupresent const ctx canvas getContext webgpu let configuration device device format ctx getPreferredFormat adapter size the size of the canvas element in pixels width canvas width height canvas height const res ctx configure configuration console log getCurrentTexture ctx getCurrentTexture const wgsl device createShaderModule code wgsltxt const pipeline device createRenderPipeline vertex module wgsl entryPoint main vs fragment module wgsl entryPoint main fs targets format bgra8unorm primitive topology triangle list let render function const commandEncoder device createCommandEncoder const textureView ctx getCurrentTexture createView const renderPassDescriptor colorAttachments view textureView loadValue r 1 g 1 b 1 a 1 storeOp store const passEncoder commandEncoder beginRenderPass renderPassDescriptor passEncoder setPipeline pipeline passEncoder draw 3 1 0 0 passEncoder endPass device queue submit commandEncoder finish requestAnimationFrame render requestAnimationFrame render
getContext webgpu let configuration device device format ctx getPreferredFormat adapter size the size of the canvas element in pixels width canvas width height canvas height const res ctx configure configuration console log getCurrentTexture ctx getCurrentTexture const wgsl device createShaderModule code wgsltxt const pipeline device createRenderPipeline vertex module wgsl entryPoint main vs fragment module wgsl entryPoint main fs targets format bgra8unorm primitive topology triangle list let render function const commandEncoder device createCommandEncoder const textureView ctx getCurrentTexture createView const renderPassDescriptor colorAttachments view textureView loadValue r 1 g 1 b 1 a 1 storeOp store const passEncoder commandEncoder beginRenderPass renderPassDescriptor passEncoder setPipeline pipeline passEncoder draw 3 1 0 0 passEncoder endPass device queue submit commandEncoder finish requestAnimationFrame render requestAnimationFrame render