liveBook · Manning

Fragment shader

As explained in Web Components in Action

A fragment shader is a GPU program that determines the color and other attributes of rasterized fragments or pixels.

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

How Web Components in Action covers it

How deep it goes
Works through a short shader’s image lookup and color calculation, but stops short of implementing a full 3D scene.
Examples
Uses a radial fade that darkens an image according to each pixel’s distance from its center.
What you can do after
Evaluate/understand how a WebGL fragment shader samples an image and calculates a pixel color.
How it connects
Connects fragment shaders to vertex shaders, texture coordinates, WebGL, HTML canvas, Three.js, and Babylon.js.

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.