A WebGL draw uses one JavaScript uniform value to make the active fragment shader render a partly transparent triangle.

Program

Uniforms are small pieces of state that JavaScript sends to a shader program. This lesson keeps the program and buffer setup implicit and focuses on one alpha value.

uniform_alpha_value.html
Visuals: generated teaching cards from captured state
  • state written by this keyframe
uniform_alpha_value.html · full logical source
1<canvas id="gl" width="320" height="180"></canvas>
2<script>
3  const gl = document.querySelector("#gl").getContext("webgl");
4  const program = gl.getParameter(gl.CURRENT_PROGRAM);
5  const alphaLocation = gl.getUniformLocation(program, "u_alpha");
6  gl.uniform1f(alphaLocation, 0.65);
7  gl.drawArrays(gl.TRIANGLES, 0, 3);
8</script>
  1. Create the WebGL context

    kf: 1event 0kind: lifecycle

    Create the WebGL context.

    3const gl = document.querySelector→ webgl("#gl").getContext("webgl");
    The canvas is ready to receive WebGL uniform and draw commands.
    The context is the object JavaScript uses to talk to WebGL.
    State after this keyframenone → webglGL context
  2. Read the active shader program

    kf: 2event 1kind: lifecycle

    Read the active shader program.

    4const program = gl.getParameter→ current program(gl.CURRENT_PROGRAM);
    The lesson uses the shader program that is already current.
    Uniforms are set on the active linked program.
    State after this keyframeimplicit setup → current programprogram
  3. Find the alpha uniform location

    kf: 3event 2kind: lifecycle

    Find the alpha uniform location.

    5const alphaLocation = gl.getUniformLocation→ u_alpha(program, "u_alpha");
    WebGL returns a location handle for the u_alpha uniform.
    The location tells WebGL which shader value JavaScript will update.
    State after this keyframeunknown → u_alphauniform location
  4. Write the alpha value

    kf: 4event 3kind: lifecycle

    Write the alpha value.

    6gl.uniform1f→ 0.65(alphaLocation, 0.65);
    The alpha uniform is set to 0.65 before drawing.
    uniform1f sends one floating-point number to the shader.
    State after this keyframeold → 0.65alpha
  5. Draw with the uniform value

    kf: 5event 4kind: lifecycle

    Draw with the uniform value.

    7gl.drawArrays→ 65 percent alpha(gl.TRIANGLES, 0, 3);
    A partly transparent triangle appears over the WebGL frame.
    The draw uses the current shader program and its alpha uniform.
    State after this keyframenot drawn → 65 percent alphatriangle
uniform location A uniform location is the handle WebGL needs before JavaScript can set a shader value.
alpha Alpha is the opacity channel in a color value.