Adding a Cube and Rendering

Back to Modules

Your First 3D Object in Three.js

Once you have your basic Three.js scene set up with a renderer, scene, and camera, the next exciting step is to add your first 3D object. A common starting point is a simple cube, which helps in understanding the core concepts of geometry and materials.

Geometry: Defining the Shape

In Three.js, `Geometry` defines the shape of a 3D object. For a cube, we use `BoxGeometry`, which takes width, height, and depth as arguments.

Code Example: Creating BoxGeometry

const geometry = new THREE.BoxGeometry(1, 1, 1); // 1 unit wide, tall, and deep

Material: Defining the Appearance

A `Material` defines how the surface of your 3D object looks and reacts to light. For a basic colored cube, `MeshBasicMaterial` or `MeshStandardMaterial` are good choices. `MeshStandardMaterial` reacts to lights, making it more realistic.

Code Example: Creating a Material

const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 }); // Green color

Mesh: Combining Shape and Appearance

A `Mesh` is the actual 3D object that gets added to your scene. It combines a `Geometry` and a `Material`.

Code Example: Creating a Mesh and Adding to Scene

const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

Rendering the Scene

Finally, to see your cube, you need to render the scene using your renderer and camera within the animation loop.

Code Example: Rendering in the Loop

function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}
animate();

Case Study: A Simple Interactive Logo

Imagine creating a simple 3D logo for a website. You could use a `BoxGeometry` for basic shapes, apply your brand colors with `MeshStandardMaterial`, and then add it to your scene. With a few lines of code in the render loop, you could even make the logo slowly rotate, adding a subtle interactive element to your page.