Skip to content

Lesson 7 of 9 · 30m

WebGL Fundamentals: The GPU Pipeline Without the Fog

Understand contexts, buffers, shaders, draw calls, uniforms, attributes, and why WebGL code looks verbose compared with canvas.

WebGL scares people because the first triangle takes a hundred lines. That verbosity is the cost of talking directly to a GPU pipeline: memory must be uploaded, shaders compiled, state bound, and draw calls issued explicitly. Once you stop expecting a scene graph, the pieces become mechanical.

The pipeline is fixed in shape

buffers -> vertex shader -> primitive assembly -> rasterization -> fragment shader -> depth/stencil/blend -> framebuffer

You do not draw a circle. You provide triangles that approximate one and shader programs that decide positions and colors. Every program pairs a compiled vertex shader with a compiled fragment shader; inspect compile and link logs because shader failure usually blanks the canvas.

Vertex shaders position geometry

#version 300 es
in vec2 a_position;
uniform vec2 u_resolution;
void main() {
  vec2 clip = (a_position / u_resolution) * 2.0 - 1.0; gl_Position = vec4(clip * vec2(1, -1), 0, 1);
}

WebGL expects clip-space positions: x and y from -1 to 1. Real applications usually use matrices, but a matrix is still just input to the same vertex-stage calculation.

Fragment shaders color fragments

#version 300 es
precision mediump float;
uniform vec4 u_color; out vec4 outColor;
void main() { outColor = u_color; }

A fragment is close to a pixel in the first mental model. Rasterization interpolates vertex outputs across triangles, then invokes the fragment shader.

Buffers and attributes are explicit plumbing

gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW)
gl.enableVertexAttribArray(location)
gl.vertexAttribPointer(location, 2, gl.FLOAT, false, 0, 0)

WebGL does not know the array contains x/y pairs until vertexAttribPointer says so. The binding, type, stride, normalization, and offset are all part of the contract.

Draw calls are performance currency

gl.useProgram(program); gl.uniform4f(colorLocation, 0.2, 0.65, 1.0, 1.0)
gl.drawArrays(gl.TRIANGLES, 0, 3)

A thousand individual draw calls can be slower than one draw call containing a thousand packed objects. WebGL is also a state machine: blending, textures, viewport, depth state, and bound buffers affect later commands. Tools such as SpectorJS can expose the exact state at a draw call.

Field notes

  • Missing fragment-shader precision declarations fail on some implementations.
  • Resizing the canvas does not update the WebGL viewport; call gl.viewport after resizing.
  • Context loss is real on mobile and GPU resets. Serious applications handle webglcontextlost and restoration.
  • Prefer WebGL2 where available for vertex array objects, instancing conveniences, modern GLSL, and fewer texture restrictions.

Was this lesson helpful?

Sign in to rate