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
varying_color_gradient.html · full logical source
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>
  1. Declare a varying color channel

    kf: 1event 0kind: lifecycle

    Declare a varying color channel.

    3varying vec3 vColor→ vColor;
    The shader pair has a color varying ready for interpolation.
    A varying is written by the vertex shader and read by the fragment shader.
    State after this keyframenone → vColorvarying
  2. Write each vertex color into the varying

    kf: 2event 1kind: lifecycle

    Write each vertex color into the varying.

    4vColor = aColor→ varying output;
    Each corner color is handed to rasterization.
    The GPU will interpolate the varying between vertices.
    State after this keyframeattribute only → varying outputvertex output
  3. Use the interpolated color in the fragment shader

    kf: 3event 2kind: lifecycle

    Use the interpolated color in the fragment shader.

    5gl_FragColor = vec4→ interpolated(vColor, 1.0);
    The fragment shader is ready to color each pixel from vColor.
    Every pixel receives a different interpolated color value.
    State after this keyframeconstant → interpolatedfragment color
  4. Draw the gradient rectangle

    kf: 4event 3kind: lifecycle

    Draw the gradient rectangle.

    6gl.drawArrays→ smooth gradient(gl.TRIANGLE_STRIP, 0, 4);
    A smooth multi-color gradient fills the rectangle.
    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.