How to Add an Object to a Three.js Scene

To display any 3D object in a Three.js application, you must insert it into the active scene graph. This article explains the fundamental steps required to create a 3D object (a mesh) and add it to your scene using the scene.add() method, ensuring it is positioned correctly for the renderer to display.

The Core Concept: scene.add()

Three.js uses a hierarchical parent-child structure called a scene graph. The THREE.Scene instance acts as the root parent. To make any 3D object visible, you must pass it as an argument to the .add() method of your active scene object.

Here is the step-by-step process to achieve this:

1. Initialize the Scene

First, you need an active scene instance. This container will hold all your cameras, lights, and 3D objects.

const scene = new THREE.Scene();

2. Create the 3D Object

In Three.js, standard visible objects are represented as a Mesh. A mesh is a combination of a Geometry (the shape) and a Material (the appearance/color).

// Define the shape (a basic cube)
const geometry = new THREE.BoxGeometry(1, 1, 1);

// Define the look (a solid green color)
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });

// Combine them into a mesh
const cube = new THREE.Mesh(geometry, material);

3. Add the Object to the Scene Graph

Use the .add() method of your scene instance to attach the mesh. Once added, the object becomes part of the scene graph and is ready to be rendered.

scene.add(cube);

4. Render the Scene

Simply adding the object is not enough; you must instruct your renderer to draw the scene from the perspective of your camera.

renderer.render(scene, camera);

Adding Multiple Objects

The scene.add() method is versatile and can accept multiple arguments at once to add several objects simultaneously:

const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
const cylinder = new THREE.Mesh(cylinderGeometry, cylinderMaterial);

// Add multiple objects in a single line
scene.add(sphere, cylinder);

If you ever need to remove an object from the active scene graph, you can use the corresponding .remove() method:

scene.remove(cube);