-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcanvas.js
More file actions
65 lines (51 loc) · 2.29 KB
/
canvas.js
File metadata and controls
65 lines (51 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
var canvas, gpu;
var shader_src;
var library, vertexFunction, fragmentFunction;
var pipelineDescriptor, pipelineState;
var vertexData, vertexBuffer;
var drawable, passDescriptor;
window.onload = function () {
canvas = document.getElementById("mycanvas");
gpu = canvas.getContext("webgpu");
shader_src = document.getElementById("library").text;
library = gpu.createLibrary(shader_src);
vertexFunction = library.functionWithName("vertex_main");
fragmentFunction = library.functionWithName("fragment_main");
pipelineDescriptor = new WebGPURenderPipelineDescriptor();
pipelineDescriptor.vertexFunction = vertexFunction;
pipelineDescriptor.fragmentFunction = fragmentFunction;
pipelineDescriptor.colorAttachments[0].pixelFormat = gpu.PixelFormatBGRA8Unorm;
pipelineState = gpu.createRenderPipelineState(pipelineDescriptor);
vertexData = new Float32Array([
// x y z 1 r g b 1
0, 0.75, 0, 1, 1, 0, 0, 1,
-0.75, -0.75, 0, 1, 0, 1, 0, 1,
0.75, -0.75, 0, 1, 0, 0, 1, 1
]);
vertexBuffer = gpu.createBuffer(vertexData);
drawable = gpu.nextDrawable();
passDescriptor = new WebGPURenderPassDescriptor();
passDescriptor.colorAttachments[0].loadAction = gpu.LoadActionClear;
passDescriptor.colorAttachments[0].storeAction = gpu.StoreActionStore;
passDescriptor.colorAttachments[0].clearColor = [0.2, 0.8, 0.8, 1.0];
passDescriptor.colorAttachments[0].texture = drawable.texture;
let commandQueue = gpu.createCommandQueue();
let commandBuffer = commandQueue.createCommandBuffer();
// Use the descriptor we created above.
let commandEncoder = commandBuffer.createRenderCommandEncoderWithDescriptor(
passDescriptor);
// Tell the encoder which state to use (i.e. shaders).
commandEncoder.setRenderPipelineState(pipelineState);
// And, lastly, the encoder needs to know which buffer
// to use for the geometry.
commandEncoder.setVertexBuffer(vertexBuffer, 0, 0);
// We know our buffer has three vertices. We want to draw them
// with filled triangles.
commandEncoder.drawPrimitives(gpu.PrimitiveTypeTriangle, 0, 3);
commandEncoder.endEncoding();
// All drawing commands have been submitted. Tell WebGPU to
// show/present the results in the canvas once the queue has
// been processed.
commandBuffer.presentDrawable(drawable);
commandBuffer.commit();
}