Multiple Programs and Regions
Second Program Switch
Two linked programs draw two triangles with different fragment behavior after WebGL switches the active program.
Program
A WebGL context can hold many linked programs, but only one program is active for a draw call. Switching programs changes the shader code that runs next.
second_program_switch.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 const colorProgram = linkProgram(colorVS, colorFS);
4 const solidProgram = linkProgram(positionVS, solidFS);
5 gl.useProgram(colorProgram);
6 gl.drawArrays(gl.TRIANGLES, 0, 3);
7 gl.useProgram(solidProgram);
8 gl.drawArrays(gl.TRIANGLES, 0, 3);
9</script>Link a program that reads color attributes
kf: 1event 0kind: lifecycleLink a program that reads color attributes.
3const colorProgram = linkProgram→ color program(colorVS, colorFS);
Program objects package vertex and fragment shader stages. State after this keyframenone → color programprogramsLink a second program with a solid fragment color
kf: 2event 1kind: lifecycleLink a second program with a solid fragment color.
4const solidProgram = linkProgram→ two programs(positionVS, solidFS);
WebGL keeps multiple program objects resident at the same time. State after this keyframeone → two programsprogramsSelect the color program
kf: 3event 2kind: lifecycleSelect the color program.
5gl.useProgram→ colorProgram(colorProgram);
useProgram changes current pipeline state. State after this keyframenone → colorProgramactive programDraw the first triangle with attribute colors
kf: 4event 3kind: lifecycleDraw the first triangle with attribute colors.
6gl.drawArrays→ colored triangle(gl.TRIANGLES, 0, 3);
The active program determines how vertex attributes become pixels. State after this keyframeclear color → colored trianglepixelsSwitch to the solid-color program
kf: 5event 4kind: lifecycleSwitch to the solid-color program.
7gl.useProgram→ solidProgram(solidProgram);
The earlier pixels remain; program state affects later draws. State after this keyframecolorProgram → solidProgramactive programDraw the second triangle with the solid program
kf: 6event 5kind: lifecycleDraw the second triangle with the solid program.
8gl.drawArrays→ two triangles(gl.TRIANGLES, 0, 3);
Two draw calls can use different linked programs in the same frame. State after this keyframeone triangle → two trianglespixels
program switch
useProgram selects the linked shader program used by subsequent draw calls.
draw order
Changing state affects future draws while earlier framebuffer pixels remain.