Textures Uniforms and Viewport
Uniform Alpha Value
Send One Number to the Shader
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
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>Create the WebGL context
kf: 1event 0kind: lifecycleCreate the WebGL context.
3const gl = document.querySelector→ webgl("#gl").getContext("webgl");
The context is the object JavaScript uses to talk to WebGL. State after this keyframenone → webglGL contextRead the active shader program
kf: 2event 1kind: lifecycleRead the active shader program.
4const program = gl.getParameter→ current program(gl.CURRENT_PROGRAM);
Uniforms are set on the active linked program. State after this keyframeimplicit setup → current programprogramFind the alpha uniform location
kf: 3event 2kind: lifecycleFind the alpha uniform location.
5const alphaLocation = gl.getUniformLocation→ u_alpha(program, "u_alpha");
The location tells WebGL which shader value JavaScript will update. State after this keyframeunknown → u_alphauniform locationWrite the alpha value
kf: 4event 3kind: lifecycleWrite the alpha value.
6gl.uniform1f→ 0.65(alphaLocation, 0.65);
uniform1f sends one floating-point number to the shader. State after this keyframeold → 0.65alphaDraw with the uniform value
kf: 5event 4kind: lifecycleDraw with the uniform value.
7gl.drawArrays→ 65 percent alpha(gl.TRIANGLES, 0, 3);
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.