WebGL Fundamentals Tutorial
Learn to create 3D graphics on the web using WebGL. A beginner's guide with interactive examples.
What is WebGL?
WebGL (Web Graphics Library) is a JavaScript API for rendering high-performance 2D and 3D graphics in web browsers without plugins. It leverages the GPU through the HTML5 canvas element.
- • Cross-platform with modern browser support
- • Uses GLSL (OpenGL Shading Language)
- • Works with JavaScript for drawing operations
- • Ideal for interactive data visualization
Getting Started
Set Up Canvas
<canvas id="glcanvas" width="800" height="600"></canvas>
Initialize WebGL
const canvas = document.getElementById('glcanvas');
const gl = canvas.getContext('webgl') ||
canvas.getContext('experimental-webgl');
if (!gl) {
alert('Your browser doesn't support WebGL!');
}
Triangle Rendering Demo
This example renders a simple triangle using WebGL. Try resizing the browser window to see how the aspect ratio changes.
Key Concepts Demonstrated
1. Buffers Objects
Stores vertex data in GPU memory
2. Shaders
GLSL programs for rendering
3. Draw Calls
Rendering the triangle geometry
Advanced Topics
Transformation Matrices
Use matrix operations to transform objects in 3D space. WebGL provides built-in matrix math utilities but you can also use libraries like gl-matrix.
// Using glMatrix
const modelMatrix = mat4.create();
mat4.translate(modelMatrix, modelMatrix, [2, 0, 0]);
Lighting and Shading
Shaders allow complex lighting calculations. This example uses a simple diffuse lighting model:
precision mediump float;
uniform vec3 uLightPos;
attribute vec3 aPosition;
attribute vec3 aNormal;
varying vec3 vLightWeighting;
void main() {
gl_Position = vec4(aPosition, 1.0);
vec3 lightVector = normalize(uLightPos - aPosition);
float diffuse = max(dot(normalize(aNormal), lightVector), 0.0);
vLightWeighting = vec3(0.5 + 0.5 * diffuse);
}