WebGL: High-Performance 3D Rendering
Leverage the power of WebGL to create immersive 3D experiences directly in the browser.
Interactive WebGL Triangle
Getting Started?
WebGL gives access to a powerful graphics API that enables hardware-accelerated rendering. With this, you can render complex 2D and 3D scenes directly in the browser.
WebGL Code Example
// Initialize WebGL context
const canvas = document.getElementById('interactiveCanvas');
const gl = canvas.getContext('webgl');
// Check if WebGL is available
if (!gl) {
console.error('WebGL is not supported in this browser.');
} else {
// Set viewport and clear color
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.clearColor(0.1, 0.1, 0.2, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.enable(gl.DEPTH_TEST);
// Define vertex and fragment shaders
const vsSource = `
attribute vec4 aVertexPosition;
void main() {
gl_Position = aVertexPosition;
}
`;
const fsSource = `
precision mediump float;
void main() {
gl_FragColor = vec4(0.8, 0.4, 0.2, 1.0);
}
`;
// Create shader program
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
// Create buffer for triangle vertices
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
const positions = [
-0.5, -0.5, 0.0,
0.5, -0.5, 0.0,
0.0, 0.5, 0.0
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
gl.useProgram(shaderProgram);
const aVertexPositionLocation = gl.getAttribLocation(shaderProgram, 'aVertexPosition');
gl.enableVertexAttribArray(aVertexPositionLocation);
gl.vertexAttribPointer(aVertexPositionLocation, 3, gl.FLOAT, false, 0, 0);
// Draw the triangle
gl.drawArrays(gl.TRIANGLES, 0, 3);
}
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
return shaderProgram;
}
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
return shader;
}
Key Features of WebGL
- Native 3D rendering in the browser without plugins
- Access to GPU acceleration for performance-intensive applications
- Full control over visuals with programmable shaders
- Cross-platform compatibility with all modern web browsers
- Integration with popular game engines and frameworks like Three.js and Babylon.js
Need Help?
For in-depth examples and interactive demos, visit our 3D Examples section.