[html] WebGL API

WebGL (Web Graphics Library) is a JavaScript API for rendering interactive 2D and 3D graphics within any compatible web browser. It is based on OpenGL ES, which is a subset of the OpenGL (Open Graphics Library) API commonly used for rendering 2D and 3D vector graphics. WebGL brings the power of hardware-accelerated graphics to the web, allowing developers to create visually stunning and interactive web applications.

Getting Started with WebGL API

To get started with WebGL, you need to have a basic understanding of HTML, CSS, and JavaScript. Here’s a simple example of setting up a WebGL context and rendering a simple triangle:

// HTML
<canvas id="myCanvas"></canvas>

// JavaScript
const canvas = document.getElementById('myCanvas');
const gl = canvas.getContext('webgl');

// Vertex Shader
const vertexShaderSource = `
  attribute vec4 position;
  void main() {
    gl_Position = position;
  }
`;

// Fragment Shader
const fragmentShaderSource = `
  void main() {
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
  }
`;

// Create and link shaders
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);

// Define geometry and render
const vertices = new Float32Array([
  0, 1,
  -1, -1,
  1, -1
]);
const vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

const position = gl.getAttribLocation(program, 'position');
gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(position);

gl.clearColor(0, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, 3);

In this example, we create a simple WebGL program to render a red triangle on a canvas element.

Key Features of WebGL API

Conclusion

WebGL API provides a powerful platform for creating interactive and visually rich web applications. Understanding the basics of WebGL programming can unlock the potential for creating stunning graphics and immersive experiences on the web.

For more information on WebGL API, refer to the official documentation on Khronos Group.