How do you use WebGL basics with an example?

This example demonstrates how to use WebGL to create a simple colored triangle on an HTML canvas. WebGL is a powerful tool for rendering 2D and 3D graphics in the browser using JavaScript.
WebGL, HTML canvas, JavaScript graphics, 2D rendering, 3D graphics, WebGL tutorial
<!DOCTYPE html> <html> <head> <title>WebGL Triangle Example</title> <style> canvas { border: 1px solid black; } </style> </head> <body> <canvas id="webgl-canvas" width="400" height="400"></canvas> <script> // Get the canvas and WebGL context var canvas = document.getElementById('webgl-canvas'); var gl = canvas.getContext('webgl'); // Set clear color to transparent black gl.clearColor(0.0, 0.0, 0.0, 0.0); gl.clear(gl.COLOR_BUFFER_BIT); // Define the geometry var vertices = new Float32Array([ 0.0, 0.5, // Vertex 1 (X, Y) -0.5, -0.5, // Vertex 2 (X, Y) 0.5, -0.5 // Vertex 3 (X, Y) ]); // Create a buffer and put the vertices in it var vertexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW); // Define the vertex shader var vertexShaderSource = ` attribute vec2 coordinates; void main(void) { gl_Position = vec4(coordinates, 0.0, 1.0); } `; // Create and compile the vertex shader var vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader, vertexShaderSource); gl.compileShader(vertexShader); // Define the fragment shader var fragmentShaderSource = ` void main(void) { gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); // Red color } `; // Create and compile the fragment shader var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragmentShader, fragmentShaderSource); gl.compileShader(fragmentShader); // Create a shader program and link shaders var shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); gl.useProgram(shaderProgram); // Bind the vertex buffer gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); var coordinates = gl.getAttribLocation(shaderProgram, "coordinates"); gl.vertexAttribPointer(coordinates, 2, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(coordinates); // Draw the triangle gl.clear(gl.COLOR_BUFFER_BIT); gl.viewport(0, 0, canvas.width, canvas.height); gl.drawArrays(gl.TRIANGLES, 0, 3); </script> </body> </html>

WebGL HTML canvas JavaScript graphics 2D rendering 3D graphics WebGL tutorial