Render Specific Objects in Three.js Using Camera Layers

This article explains how to selectively render specific 3D objects in Three.js by manipulating the camera’s layers bitmask. You will learn how to assign objects to distinct layers and configure the camera using methods like enable(), disable(), and set() to control which objects are visible during rendering.

In Three.js, every Object3D (including meshes, lights, and cameras) is assigned to one or more of 32 available layers (numbered 0 to 31). By default, all objects and cameras are assigned to layer 0. A camera will only render objects that share at least one active layer with it.

Step 1: Assign Objects to Specific Layers

To control which objects are rendered, you must first assign them to specific layers using the layers.set() method.

// Create two different meshes
const redCube = new THREE.Mesh(geometry, redMaterial);
const blueCube = new THREE.Mesh(geometry, blueMaterial);

// Assign redCube to Layer 1 and blueCube to Layer 2
redCube.layers.set(1);
blueCube.layers.set(2);

scene.add(redCube);
scene.add(blueCube);

Step 2: Manipulate the Camera’s Layers Bitmask

You can control the camera’s active layers by interacting with its layers object. Three.js provides three primary methods to manipulate the camera’s active layers:

1. camera.layers.set(channel)

This method disables all current layers and enables only the single specified layer channel.

// The camera will now render ONLY objects on Layer 1 (the red cube)
camera.layers.set(1);

2. camera.layers.enable(channel)

This method enables an additional layer channel without disabling the layers that are already active.

// Camera currently renders Layer 1. 
// This adds Layer 2, meaning the camera now renders both Layer 1 and Layer 2.
camera.layers.enable(2);

3. camera.layers.disable(channel)

This method deactivates a specific layer channel on the camera.

// The camera will stop rendering objects on Layer 1, but will keep rendering Layer 2.
camera.layers.disable(1);

4. camera.layers.toggle(channel)

This method toggles the membership of a layer channel (enables it if it is disabled, or disables it if it is enabled).

// Toggles the visibility of Layer 2
camera.layers.toggle(2);

Under the Hood: The Bitmask

Three.js stores layer states internally as a 32-bit integer mask. Each bit in the 32-bit integer corresponds to a layer from 0 to 31. When a camera renders a scene, it performs a bitwise AND operation between the camera’s layer mask and each object’s layer mask:

// Check if an object and camera share an active layer
const isVisible = (camera.layers.mask & object.layers.mask) !== 0;

If the result of this bitwise operation is non-zero, the object is rendered; otherwise, it is ignored during the render pass. This makes layer filtering incredibly fast and performance-friendly.