Three.js Multi-Pass Rendering (Stencil Masking & Depth Pre-Pass)
Multi-pass rendering in Three.js with a stencil-buffer X-ray lens that reveals hidden internals only inside a mask, plus an optional depth pre-pass that cuts overdraw by shading each pixel once.
Key topics: three.js stencil buffer, stencil mask, depth prepass, multi-pass rendering, xray effect, overdraw
Game Over
What this code does
- Stencil Buffer: the renderer is created with `stencil: true`, an 8-bit per-pixel tag that masks later draws.
- Mask Pass: the lens writes 1 into the stencil with colorWrite and depthWrite off, using `stencilZPass: ReplaceStencilOp`.
- Masked Pass: inner parts use `stencilFunc: EqualStencilFunc` with ref 1, so they appear only inside the lens.
- Render Order: `renderOrder` makes the mask draw before the masked content within the same frame.
- Depth Pre-Pass: a colourless depth-only pass fills the Z-buffer so the full pass shades just the nearest fragment (early-Z).
- Controls: lens on/off, radius, pointer follow, depth pre-pass and overdraw layers.
Related Demos
Continue Learning
JavaScript Implementation
// Stencil masking: a hidden mask writes 1, then the masked content draws only where stencil == 1
const mask = new THREE.Mesh(new THREE.CircleGeometry(1, 64), new THREE.MeshBasicMaterial({
colorWrite: false, depthWrite: false,
stencilWrite: true, stencilRef: 1,
stencilFunc: THREE.AlwaysStencilFunc, stencilZPass: THREE.ReplaceStencilOp
}))
mask.renderOrder = 1
const inside = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial({
stencilWrite: true, stencilRef: 1, stencilFunc: THREE.EqualStencilFunc, depthTest: false
}))
inside.renderOrder = 2
scene.add(mask, inside)
// Depth pre-pass: render once with colorWrite: false, then again with depthFunc LessEqual