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 66 67 68 69 70 71 72
| const canvas = document.querySelector("canvas"); const gl = canvas.getContext("webgl");
const vertex = ` attribute vec2 position;
void main() { gl_PointSize = 1.0; gl_Position = vec4(position, 1.0, 1.0); } `;
const fragment = ` precision mediump float;
void main() { gl_FragColor = vec4(0.0, 1.0, 1.0, 1.0); } `;
const vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader, vertex); gl.compileShader(vertexShader);
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragmentShader, fragment); gl.compileShader(fragmentShader);
const program = gl.createProgram(); gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program); gl.useProgram(program);
const vertices = [ [-1, -1], [-1, 0], [0, 0], [0, -1], ];
const points = vertices.flat(); const triangles = earcut(points);
const position = new Float32Array(points); const cells = new Uint16Array(triangles);
const pointBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, pointBuffer); gl.bufferData(gl.ARRAY_BUFFER, position, gl.STATIC_DRAW);
const cellsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cellsBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, cells, gl.STATIC_DRAW);
const vPosition = gl.getAttribLocation(program, "position"); gl.vertexAttribPointer(vPosition, 2, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(vPosition);
gl.clear(gl.COLOR_BUFFER_BIT); gl.drawElements(gl.TRIANGLES, cells.length, gl.UNSIGNED_SHORT, 0);
|