Vertex Shaders in Raw WebGL2
So far every shader in this course has been a fragment shader on a rectangle that covers the frame. Real scenes are made of meshes: thousands of triangles whose corners (vertices) come from the CPU in buffers. The program that decides where each vertex lands on screen is the vertex shader. It runs once per vertex, before rasterization, and its outputs are interpolated across each triangle for the fragment shader.
This lesson draws with raw WebGL2, no library, so you can see every piece the engines hide: buffers, attributes, uniforms, varyings and gl_Position.
The contract of a vertex shader
| Piece | GLSL ES 3.00 | Meaning |
|---|---|---|
| attribute | in vec2 aPos; |
per-vertex data read from a buffer (position, normal, UV, color) |
| uniform | uniform float uTime; |
the same value for every vertex in the draw |
| varying (output) | out vec3 vColor; |
a value handed to the rasterizer, interpolated per pixel |
| built-in output | gl_Position |
the vertex position in clip space (vec4) |
The fragment shader receives the varying with the matching name declared as in vec3 vColor;. The names and types must match exactly, or the program fails to link, which is a separate step after both stages compile.
gl_Position is in clip space: after the GPU divides by w, the visible region is -1..1 in x and y (and -1..1 in z for WebGL/OpenGL). With w = 1 you are writing normalized device coordinates (NDC) directly: (-1, -1) is the bottom-left corner of the canvas and (1, 1) the top-right. The Matrices in Shaders lesson shows how 3D positions get there.
A colored triangle
Three vertices, each with a position and a color, packed in one buffer as x, y, r, g, b. A vertex array object (VAO) remembers how the buffer is split into attributes, so drawing later is one bindVertexArray plus one drawArrays.
<style>html, body { margin: 0; height: 100%; background: #111 } canvas { display: block; width: 100%; height: 100% }</style>
<canvas id="c"></canvas>
<script>
const canvas = document.getElementById('c');
canvas.width = innerWidth; canvas.height = innerHeight;
const gl = canvas.getContext('webgl2');
const vsSource = `#version 300 es
in vec2 aPos; // location 0
in vec3 aColor; // location 1
out vec3 vColor; // handed to the rasterizer
void main() {
vColor = aColor;
gl_Position = vec4(aPos, 0.0, 1.0); // already in clip space
}`;
const fsSource = `#version 300 es
precision highp float;
in vec3 vColor; // interpolated across the triangle
out vec4 outColor;
void main() {
outColor = vec4(vColor, 1.0);
}`;
function compile(type, source) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.error(gl.getShaderInfoLog(shader));
}
return shader;
}
const program = gl.createProgram();
gl.attachShader(program, compile(gl.VERTEX_SHADER, vsSource));
gl.attachShader(program, compile(gl.FRAGMENT_SHADER, fsSource));
gl.bindAttribLocation(program, 0, 'aPos');
gl.bindAttribLocation(program, 1, 'aColor');
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) console.error(gl.getProgramInfoLog(program));
// x y r g b
const data = new Float32Array([
-0.8, -0.7, 1, 0, 0,
0.8, -0.7, 0, 1, 0,
0.0, 0.8, 0, 0, 1,
]);
const vao = gl.createVertexArray();
gl.bindVertexArray(vao);
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
const stride = 5 * 4; // 5 floats of 4 bytes per vertex
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, stride, 0); // aPos: 2 floats at byte 0
gl.enableVertexAttribArray(1);
gl.vertexAttribPointer(1, 3, gl.FLOAT, false, stride, 8); // aColor: 3 floats at byte 8
gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(0.07, 0.07, 0.07, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.useProgram(program);
gl.drawArrays(gl.TRIANGLES, 0, 3);
</script>The vertex shader only ran three times. The fragment shader ran for every covered pixel, and each pixel received a blend of the three corner colors weighted by how close it is to each corner (barycentric interpolation). The GPU also corrects that blend for perspective, so textures do not swim on slanted 3D surfaces. If you want a varying to stay constant across a triangle (an object ID, a flat-shaded normal), declare it flat out / flat in.
Notice also that the triangle is stretched on a wide canvas: NDC always spans -1..1, whatever the aspect ratio. The projection matrix normally fixes this.
An animated wave grid
The vertex shader can move vertices every frame. Here a flat grid of 64 × 64 points is built once on the CPU, and the vertex shader raises each point with two sine waves driven by a uTime uniform. The CPU never touches the positions again: only one float changes per frame.
<style>html, body { margin: 0; height: 100%; background: #0b1020 } canvas { display: block; width: 100%; height: 100% }</style>
<canvas id="c"></canvas>
<script>
const canvas = document.getElementById('c');
canvas.width = innerWidth; canvas.height = innerHeight;
const gl = canvas.getContext('webgl2');
const vs = `#version 300 es
in vec2 aGrid; // grid coordinate, -1..1 in x and z
uniform float uTime;
uniform float uAspect;
out float vHeight;
void main() {
float h = 0.12 * sin(aGrid.x * 6.0 + uTime * 2.0)
+ 0.08 * sin(aGrid.y * 9.0 - uTime * 1.3);
vHeight = h;
// cheap fake perspective: tilt the grid and shrink rows that are farther away
float depth = aGrid.y * 0.5 + 1.5; // 1 (near) .. 2 (far)
vec2 p = vec2(aGrid.x, aGrid.y * 0.45 + h * 2.0 - 0.1) / depth;
gl_Position = vec4(p.x / uAspect * 1.6, p.y, 0.0, 1.0);
gl_PointSize = 3.0;
}`;
const fs = `#version 300 es
precision highp float;
in float vHeight;
out vec4 outColor;
void main() {
vec3 low = vec3(0.1, 0.3, 0.8), high = vec3(0.6, 1.0, 0.9);
outColor = vec4(mix(low, high, vHeight * 3.0 + 0.5), 1.0);
}`;
function compile(type, source) {
const s = gl.createShader(type);
gl.shaderSource(s, source);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) console.error(gl.getShaderInfoLog(s));
return s;
}
const program = gl.createProgram();
gl.attachShader(program, compile(gl.VERTEX_SHADER, vs));
gl.attachShader(program, compile(gl.FRAGMENT_SHADER, fs));
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) console.error(gl.getProgramInfoLog(program));
const N = 64, points = new Float32Array(N * N * 2);
for (let j = 0; j < N; j++) for (let i = 0; i < N; i++) {
points[(j * N + i) * 2] = i / (N - 1) * 2 - 1;
points[(j * N + i) * 2 + 1] = j / (N - 1) * 2 - 1;
}
const vao = gl.createVertexArray();
gl.bindVertexArray(vao);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, points, gl.STATIC_DRAW);
const loc = gl.getAttribLocation(program, 'aGrid'); // let the linker pick, then ask
gl.enableVertexAttribArray(loc);
gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
const uTime = gl.getUniformLocation(program, 'uTime');
const uAspect = gl.getUniformLocation(program, 'uAspect');
gl.useProgram(program);
gl.uniform1f(uAspect, canvas.width / canvas.height);
function frame(ms) {
gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(0.04, 0.06, 0.12, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.uniform1f(uTime, ms / 1000); // the only per-frame upload
gl.drawArrays(gl.POINTS, 0, N * N);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
</script>Two details worth copying into your own code:
- Uniform locations are looked up once, after linking, and reused every frame.
gl.uniform*always writes to the currently bound program, so calluseProgramfirst. getAttribLocationversusbindAttribLocation: either let the linker choose and ask (second example), or force a location before linking (first example). In GLSL ES 3.00 you can also writelayout(location = 0) in vec2 aPos;in the shader itself.
Tip: Change
gl.POINTStogl.LINE_STRIPto see the vertex order, and raise the wave amplitude to0.3. Real terrain or water meshes use index buffers (gl.ELEMENT_ARRAY_BUFFER+drawElements) to build triangles from the same grid without repeating vertices.
What runs where
| Stage | Runs | Typical work |
|---|---|---|
| CPU (JavaScript, C++, C#) | once per draw | upload buffers once, set uniforms, issue the draw call |
| vertex shader | once per vertex | transform positions, skinning, wind, waves, pass varyings |
| rasterizer (fixed function) | once per triangle | clip, divide by w, find covered pixels, interpolate varyings |
| fragment shader | once per covered pixel | lighting, texturing, effects |
Moving work up this table (from per-pixel to per-vertex, or from per-vertex to per-draw) is one of the oldest optimizations in graphics. Gouraud shading computed lighting per vertex and interpolated the color; it is cheap but loses small highlights, which is why modern games light per pixel.
Common errors
- Nothing drawn, no error: the triangle is outside
-1..1,wis 0, or you forgotuseProgram/bindVertexArray. Clear to a non-black color so you can tell "nothing drawn" from "drew black". - Link error about a varying: the vertex
outand fragmentindiffer in name or type. getUniformLocationreturnsnull: the compiler removed a uniform the shader never uses. Setting anulllocation is silently ignored, which hides typos.
Test yourself
How many times does the vertex shader run when you draw one triangle with drawArrays(gl.TRIANGLES, 0, 3) covering 10,000 pixels?
- Once
- 3 times
- 10,000 times
- 10,003 times
What does the GPU do with a vertex shader's out variables before the fragment shader sees them?
- Nothing; every pixel gets vertex 0's value
- Interpolates them across the triangle (perspective-correct by default)
- Averages all three and gives every pixel the same value
- Sends them back to the CPU
With gl_Position = vec4(p, 0.0, 1.0), where is p = (1.0, 1.0) on the canvas?
- Bottom-left
- Center
- Top-right corner
- Off screen