Skip to content

Stencil

In 3D graphics there are various data buffers, for example, the z-buffer or depth buffer is used to determine which parts of objects are renderered via a depth test. The stencil buffer is a data buffer which allows for different effects such as masking, planar reflections, outlines, portals, and shadows. It is often used in tandem with the z-buffer.

mask
outlines

To use the stencil buffer in three.js, it needs to be enabled via the renderer’s constructor.

const renderer = new WebGLRenderer({
stencil: true,
});

The stencil buffer is an opt-in feature because it requires extra space which may go unused if the application doesn’t need to use the stencil buffer.

With the stencil buffer enabled, each material that makes use of the stencil buffer needs to define how it interacts with it. This is done through the various stencil* properties of the material, the most important being stencilWrite.

// could be any three.js material
const material = new MeshBasicMaterial({
stencilWrite: true,
});

Enabling the stencilWrite property allows the material to read and write to the stencil buffer.

You can read more about the stencil properties in the three.js material docs page.

Notably there are properties that determine what value to use when comparing against the stencil buffer, what gl function to use for the comparison, and what operation to perform if the depth test passes or fails and the stencil function passes.