Creating a WebGL2 Rendering Context
This code demonstrates how to create a WebGL2 rendering context from a canvas element. If the browser does not support WebGL2, an error message is logged.
const canvas = document.createElement('canvas');
const gl = canvas.getContext('webgl2');
if (!gl) {
console.error('WebGL2 is not supported by your browser.');
}
Setting Up Shaders
This code sets up basic vertex and fragment shaders, compiles them, and links them into a WebGL2 program. The shaders are then used in the rendering context.
const vertexShaderSource = `
attribute vec4 a_position;
void main() {
gl_Position = a_position;
}
`;
const fragmentShaderSource = `
void main() {
gl_FragColor = vec4(1, 0, 0.5, 1);
}
`;
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexShaderSource);
gl.compileShader(vertexShader);
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentShaderSource);
gl.compileShader(fragmentShader);
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
gl.useProgram(program);
Drawing a Simple Triangle
This code creates a buffer for a simple triangle's vertices, binds it, and sets up the vertex attribute pointers. Finally, it clears the canvas and draws the triangle.
const vertices = new Float32Array([
0, 1, 0,
-1, -1, 0,
1, -1, 0
]);
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
const positionLocation = gl.getAttribLocation(program, 'a_position');
gl.enableVertexAttribArray(positionLocation);
gl.vertexAttribPointer(positionLocation, 3, gl.FLOAT, false, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, 3);