Want to fade an image toward black around its center? In WebGL, a vertex shader positions a flat square over the canvas, and a fragment shader sets the color of each pixel drawn on it. section 15.2
The fragment shader reads a source pixel from the image, measures its texture coordinate’s distance from the center, then uses that distance to scale the pixel’s color. That produces the radial fade. section 15.2
Listing 15.1. An example WebGL shader (continued)
precision mediump float;
varying vec2 v_texCoord; #1
uniform sampler2D u_image0; #2
void main(void) {
vec4 sourcePixel = #3
texture2D(u_image0, v_texCoord);
float multiply = 1.0;
vec2 center = vec2(0.5, 0.5);
float dist = distance(v_texCoord, center);
gl_FragColor = (0.6-dist) * sourcePixel; #4
}
Follow `v_texCoord` from the image lookup through `distance(...)` to the final `gl_FragColor` assignment. section 15.2
This small effect hints at the work behind a full 3D scene. For more complex rendering, Three.js or Babylon.js can handle much of the low-level WebGL work instead of requiring you to write shaders directly. section 15.2
