Two overlapping triangles draw out of order, but the depth test keeps the closer triangle visible where they overlap.

Program

The depth buffer stores a depth value per pixel. With depth testing enabled, WebGL can reject fragments that are farther away.

depth_test_overlap.html
Visuals: generated teaching cards from captured state
  • state written by this keyframe
depth_test_overlap.html · full logical source
1<canvas id="stage" width="360" height="210"></canvas>
2<script>
3  gl.enable(gl.DEPTH_TEST);
4  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
5  gl.drawArrays(gl.TRIANGLES, 0, 3);
6  gl.drawArrays(gl.TRIANGLES, 3, 3);
7</script>
  1. Enable depth testing

    kf: 1event 0kind: lifecycle

    Enable depth testing.

    3gl.enable→ enabled(gl.DEPTH_TEST);
    The depth test is active for later fragments.
    Depth testing compares incoming fragment depth with the stored depth buffer value.
    State after this keyframedisabled → enableddepth test
  2. Clear color and depth buffers together

    kf: 2event 1kind: lifecycle

    Clear color and depth buffers together.

    4gl.clear→ 1.0 everywhere(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    Both color and depth storage are reset.
    A fresh depth buffer starts every pixel at the far depth value.
    State after this keyframeold values → 1.0 everywheredepth buffer
  3. Draw the nearer teal triangle first

    kf: 3event 2kind: lifecycle

    Draw the nearer teal triangle first.

    5gl.drawArrays→ near triangle depth(gl.TRIANGLES, 0, 3);
    The near triangle writes color and close depth values.
    Later fragments must pass the depth comparison to replace these pixels.
    State after this keyframeempty → near triangle depthdepth buffer
  4. Draw the farther orange triangle second

    kf: 4event 3kind: lifecycle

    Draw the farther orange triangle second.

    6gl.drawArrays→ near triangle still on top(gl.TRIANGLES, 3, 3);
    The far triangle appears only where it does not sit behind the nearer one.
    Depth testing keeps closer fragments even when draw order changes.
    State after this keyframenear triangle → near triangle still on toppixels
depth buffer The depth buffer stores the current depth value for each pixel.
depth test The depth test decides whether a fragment is close enough to update a pixel.