Per-Pixel Effects
Varying Color Gradient
A vertex shader writes vColor, and the fragment shader reads the interpolated value to fill a rectangle with a smooth corner gradient.
Program
Varyings bridge vertex and fragment shaders. The GPU interpolates each varying for every covered pixel.
varying_color_gradient.html
Visuals: generated teaching cards from captured state
- state written by this keyframe
1<canvas id="stage" width="360" height="210"></canvas>
2<script>
3 varying vec3 vColor;
4 vColor = aColor;
5 gl_FragColor = vec4(vColor, 1.0);
6 gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
7</script>Declare a varying color channel
kf: 1event 0kind: lifecycleDeclare a varying color channel.
3varying vec3 vColor→ vColor;
A varying is written by the vertex shader and read by the fragment shader. State after this keyframenone → vColorvaryingWrite each vertex color into the varying
kf: 2event 1kind: lifecycleWrite each vertex color into the varying.
4vColor = aColor→ varying output;
The GPU will interpolate the varying between vertices. State after this keyframeattribute only → varying outputvertex outputUse the interpolated color in the fragment shader
kf: 3event 2kind: lifecycleUse the interpolated color in the fragment shader.
5gl_FragColor = vec4→ interpolated(vColor, 1.0);
Every pixel receives a different interpolated color value. State after this keyframeconstant → interpolatedfragment colorDraw the gradient rectangle
kf: 4event 3kind: lifecycleDraw the gradient rectangle.
6gl.drawArrays→ smooth gradient(gl.TRIANGLE_STRIP, 0, 4);
The four corner colors blend through per-pixel varying interpolation. State after this keyframeclear color → smooth gradientpixels
varying
A varying carries interpolated values from vertex shader to fragment shader.
interpolation
Interpolation computes per-pixel values between primitive vertices.