How to Clear Only the Depth Buffer in Three.js

In Three.js, rendering layered scenes, HUDs, or complex visual effects often requires clearing the depth buffer while preserving the color buffer. This article provides a quick and direct guide on how to configure your WebGLRenderer and use the clearDepth() method to clear only the depth buffer during your render loop.

Step 1: Disable Auto-Clear on the Renderer

By default, the Three.js WebGLRenderer automatically clears the color, depth, and stencil buffers before rendering a new frame. To manually control when and what gets cleared, you must set renderer.autoClear to false.

const renderer = new THREE.WebGLRenderer();
renderer.autoClear = false;

Step 2: Clear the Depth Buffer in the Render Loop

Once auto-clear is disabled, you must manually manage your rendering sequence. In your animation loop, you will typically:

  1. Clear the entire screen at the start of the frame.
  2. Render your primary scene.
  3. Clear only the depth buffer using renderer.clearDepth().
  4. Render your overlay or secondary scene on top.

Here is the implementation:

function animate() {
    requestAnimationFrame(animate);

    // 1. Manually clear the color and depth buffers at the start of the frame
    renderer.clear();

    // 2. Render the background or primary 3D scene
    renderer.render(backgroundScene, camera);

    // 3. Clear ONLY the depth buffer
    renderer.clearDepth();

    // 4. Render the foreground scene (e.g., UI, HUD, or overlays)
    // This will draw on top of the primary scene regardless of physical depth
    renderer.render(foregroundScene, camera);
}

Alternative Method: Using renderer.clear()

As an alternative to renderer.clearDepth(), you can use the generic clear method by passing boolean arguments for color, depth, and stencil buffers:

// Arguments: (color, depth, stencil)
renderer.clear(false, true, false); 

Both methods achieve the same result: they reset the depth buffer so that subsequent draw calls are rendered on top of the existing color buffer without depth testing interference from the previously rendered objects.