liveBook · Manning

Vertex shader

As explained in Web Components in Action

A vertex shader is a GPU program that transforms or processes the vertices of rendered geometry.

Want a WebGL image effect? Start by giving the pixels somewhere to go. A vertex shader processes points in space; for this simple effect, those points form a flat square the size of the canvas. WebGL uses the GPU for rendering that would be slow to do on the CPU. section 15.2

Listing 15.1. An example WebGL shader
attribute vec2 a_position;                          #1
attribute vec2 a_texCoord;
uniform vec2 u_resolution;
varying vec2 v_texCoord;
uniform vec2 offset;

void main() {                                       #2
   vec2 zeroToOne = a_position / u_resolution;
   vec2 zeroToTwo = zeroToOne * 2.0;
   vec2 clipSpace = zeroToTwo - 1.0 + offset;
   gl_Position = vec4(clipSpace.x * 1.0, clipSpace.y * -1.0, 0.0, 1.0);
   v_texCoord = a_texCoord;
}

Follow the positions through the shader: divide by canvas resolution, convert to clip space, assign gl_Position, then pass texture coordinates onward. section 15.2

What colors the square? A complementary fragment shader reads the image and sets pixel colors, producing a radial fade to black. This small effect shows why larger 3D scenes commonly rely on higher-level libraries such as Three.js or Babylon.js instead of hand-written shaders. section 15.2

How Web Components in Action covers it

How deep it goes
Works through coordinate conversion and texture-coordinate passing in a shader listing, but stops short of a full 3D scene.
Examples
Uses a canvas-sized square and a paired fragment shader that fades an image toward black around a center point.
What you can do after
Evaluate/understand it as the vertex-processing half of a simple WebGL effect and recognize when a higher-level 3D library avoids shader work.
How it connects
Connects WebGL, GPU rendering, clip space, texture coordinates, fragment shaders, and HTML canvas.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.