Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 50 ยท WebGL and Real-Time Graphics

WebGL Overview

Understand how WebGL draws with the GPU: contexts, buffers, shaders, programs, attributes, draw calls and the state machine, ending with a live triangle.

So far you have drawn pixels with JavaScript on the CPU: loops over pixels, edge functions, z-buffers. That is perfect for learning, but it is slow. A 1920 by 1080 screen has over two million pixels, and a game needs to update all of them 60 times a second. The CPU has a handful of fast cores. A GPU (graphics processing unit) has thousands of small cores that all run the same program on different data at the same time, which is exactly what rasterization needs: the same shader for every vertex, the same shader for every fragment.

WebGL is how a web page talks to that hardware. It is a JavaScript API for the <canvas> element, modeled on OpenGL ES, the graphics API used in phones. It works in every modern browser without plugins. WebGL does not draw "a cube" or "a circle": it draws points, lines and triangles, and you tell it how by writing small programs called shaders, the programmable stages of the rasterization pipeline you just studied.

CPU rendering versus GPU rendering

CPU (Canvas 2D, our JavaScript renderers) GPU (WebGL)
Model A few fast cores, general code Thousands of simple cores, same code on many items
You write The loops over pixels A small program per vertex and per fragment
Good at Branchy logic, small drawings, UI Millions of triangles and pixels per frame
Data JavaScript arrays and objects Buffers and textures held in GPU memory

The price of the GPU is a new way of thinking. You do not loop over pixels. You upload data once, describe what to draw, and ask the GPU to draw it. The shaders run on the graphics card, and you cannot print from inside them or use ordinary JavaScript.

Getting a context

Every WebGL program starts with a canvas and a rendering context:

JavaScript
const canvas = document.querySelector("canvas");
const gl = canvas.getContext("webgl");
if (!gl) {
  // WebGL is unavailable (old browser, blocked GPU, ...): show a message
}

WebGL comes in two versions. WebGL 1 is based on OpenGL ES 2.0, WebGL 2 on OpenGL ES 3.0 and adds many conveniences (more texture formats, #version 300 es shaders, instancing built in). This course uses WebGL 1 style code, which is also accepted by WebGL 2 contexts, because it runs everywhere and shows the same concepts. Every call you make is a method on gl, and constants live on it too: gl.TRIANGLES, gl.FLOAT, gl.COLOR_BUFFER_BIT.

WebGL is a state machine

This is the most important mental model. The context holds a lot of current state: which buffer is "bound", which shader program is "in use", which texture is active, whether the depth test is enabled, the clear color and so on. Most functions do not take everything they need as arguments. Instead, you set the state first and then call a function that works on the current state:

JavaScript
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);   // make this buffer "the current one"
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW); // ...then fill whichever buffer is current

bufferData has no argument naming the buffer; it uses whatever is bound to ARRAY_BUFFER. That feels odd at first, but it is how OpenGL has worked for decades. Remember it as: bind, then act. Forgetting to bind (or binding the wrong thing) is the most common beginner bug, and the errors usually appear as a blank canvas.

The ingredients of a draw

To draw one thing you need four ingredients.

flowchart LR
  A["JavaScript arrays<br/>(Float32Array)"] -->|"bufferData"| B["Buffer<br/>(GPU memory)"]
  C["GLSL source<br/>(vertex + fragment)"] -->|"compile + link"| D["Program"]
  B -->|"attribute pointers"| E["gl.drawArrays<br/>(draw call)"]
  D --> E
  E --> F["Pixels in<br/>the canvas"]

Data goes into buffers, code is compiled into a program, and a draw call combines them.

1. Buffers

A buffer is a block of GPU memory. You fill it from a typed array, usually Float32Array, with the vertex data:

JavaScript
const positions = new Float32Array([
   0.0,  0.7,     // vertex 0: x, y
  -0.7, -0.6,     // vertex 1
   0.7, -0.6,     // vertex 2
]);
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);

STATIC_DRAW is a hint that you will upload once and draw many times (use DYNAMIC_DRAW for data you rewrite often).

2. Shaders and the program

Shaders are written in GLSL (OpenGL Shading Language), a C-like language, as strings in your JavaScript. A vertex shader runs once per vertex and sets gl_Position; a fragment shader runs once per covered pixel and sets gl_FragColor. You compile both and link them into a program:

JavaScript
function compile(type, source) {
  const shader = gl.createShader(type);
  gl.shaderSource(shader, source);
  gl.compileShader(shader);
  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    throw new Error(gl.getShaderInfoLog(shader));   // GLSL errors appear here
  }
  return shader;
}
const program = gl.createProgram();
gl.attachShader(program, compile(gl.VERTEX_SHADER, vertexSource));
gl.attachShader(program, compile(gl.FRAGMENT_SHADER, fragmentSource));
gl.linkProgram(program);

Always check the compile status and print the info log, because a broken shader fails silently otherwise. The next lesson, Shaders and GLSL Basics, covers the language itself.

3. Connecting buffers to shader inputs

The vertex shader declares attributes, its per-vertex inputs. You tell WebGL which buffer feeds which attribute and how to read it:

JavaScript
const loc = gl.getAttribLocation(program, "aPosition");
gl.enableVertexAttribArray(loc);
gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
//                    ^size  ^type   ^normalize ^stride ^offset

Here the attribute reads 2 floats per vertex from the currently bound ARRAY_BUFFER (the state machine again). With a stride and offset you can pack several attributes, such as position and color, in one interleaved buffer.

4. The draw call

Finally:

JavaScript
gl.useProgram(program);
gl.drawArrays(gl.TRIANGLES, 0, 3);    // mode, first vertex, vertex count

This is a draw call: the GPU runs the vertex shader 3 times, assembles one triangle, rasterizes it and runs the fragment shader for every pixel it covers. Draw calls are relatively expensive to issue from JavaScript, so real applications batch geometry into as few calls as possible.

Clip space, not pixels

The coordinates a WebGL vertex shader outputs are in clip space. For a 2D drawing without any matrices, that means x and y run from -1 to +1 across the canvas regardless of its pixel size: (-1, -1) is the bottom-left, (1, 1) the top-right, (0, 0) the center, and y points up. That is why the triangle positions above are small fractions. In 3D you will multiply by matrices to get there, as covered in projection and the coordinate systems lesson.

Your first triangle

Here is the complete program: a triangle with a different color on each corner. The vertex shader simply passes the position on and hands the color to the fragment shader as a varying. The rasterizer interpolates it across the triangle, which is the same barycentric blending as in triangle rasterization, done by the hardware. Notice that the program never loops over pixels.

If your browser blocks WebGL, the demo prints a message instead of drawing.

Your first WebGL triangle

The three numbers per vertex after the position are red, green and blue. Edit them and rerun, or add a fourth vertex pair and change the count: that is all it takes to experiment.

Primitive types

The first argument of drawArrays says how to group vertices into shapes. With the same vertex list, different modes give very different pictures. The demo below draws six vertices in each mode so you can see how TRIANGLE_STRIP and TRIANGLE_FAN reuse vertices (a strip of n vertices makes n - 2 triangles, instead of needing 3 * (n - 2) vertices with plain TRIANGLES).

WebGL primitive modes

Try LINES (pairs of vertices make separate segments), LINE_STRIP (connected), LINE_LOOP (connected and closed) and TRIANGLE_FAN (all triangles share the first vertex). Notice also that WebGL cannot draw quads directly: a rectangle is two triangles.

Common mistakes

  • Blank canvas. Check the console for a shader info log, make sure you called useProgram, that the vertex count is right, and that your coordinates are inside -1..1.
  • Wrong buffer bound when calling vertexAttribPointer: the pointer captures whatever is bound to ARRAY_BUFFER at that moment.
  • Forgetting precision mediump float; in the fragment shader of WebGL 1, which fails to compile.
  • Not clearing the canvas: set the viewport and clear at the start of each frame.
  • Wrong typed array: gl.FLOAT data must come from a Float32Array, not a plain array.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does it mean that WebGL is a state machine?

    gl.bindBuffer selects the current buffer and gl.bufferData then fills whichever buffer is bound. The same pattern holds for programs, textures and settings.
  2. 2. Which coordinate range does WebGL use for x and y in clip space when no matrices are applied?

    Clip space (after the divide, normalized device coordinates) covers -1..1 on each axis regardless of the canvas size, and y points up.
  3. 3. What are the two shaders every WebGL program needs?

    The vertex shader positions each vertex (gl_Position) and the fragment shader colors each covered pixel (gl_FragColor).
  4. 4. How many triangles does gl.drawArrays(gl.TRIANGLE_STRIP, 0, 6) draw?

    A strip reuses the previous two vertices, so n vertices make n - 2 triangles: 6 - 2 = 4.
  5. 5. Why should you check gl.getShaderParameter(shader, gl.COMPILE_STATUS) and print the info log?

    Shaders compile at runtime by the GPU driver. A syntax error does not throw an exception by itself, so you must ask for the status and read the log.

Summary

  • A GPU runs one small program on thousands of vertices or pixels in parallel; WebGL exposes it to JavaScript through canvas.getContext("webgl").
  • WebGL is a state machine: bind a resource, then call the function that works on it.
  • A draw needs buffers (vertex data in GPU memory), a program (compiled vertex + fragment shaders), attribute pointers connecting the two, and a draw call.
  • Vertex shader outputs are in clip space (-1..1, y up); varyings are interpolated across the triangle by the rasterizer.
  • Primitive modes (POINTS, LINES, TRIANGLES, TRIANGLE_STRIP, TRIANGLE_FAN, ...) say how vertices are grouped.
  • Always check compile and link status and read the info log.

Next, learn the language of the GPU in Shaders and GLSL Basics.