How to Create a Cube in Three.js Using BoxGeometry
Creating a 3D cube is the fundamental starting point for learning
Three.js. This guide provides a direct, step-by-step walkthrough of how
to instantiate a basic 3D cube using the built-in
BoxGeometry class, pair it with a material, combine them
into a mesh, and render it inside a Three.js scene.
Step 1: Define the Box Geometry
The BoxGeometry class is used to create the shape of the
cube. It takes three primary parameters: width, height, and depth.
// Create a cube geometry with a size of 1 unit on all sides
const geometry = new THREE.BoxGeometry(1, 1, 1);Step 2: Create a Material
To make the geometry visible, you must define a material. The
material determines how the cube’s surface looks, including its color
and how it reacts to light. For a simple cube that does not require
light sources to be visible, use MeshBasicMaterial.
// Create a solid green material
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });Step 3: Combine Geometry and Material into a Mesh
A Mesh is an object that takes a geometry and applies a
material to it, which can then be inserted into your 3D scene.
// Combine geometry and material to create the cube mesh
const cube = new THREE.Mesh(geometry, material);Step 4: Add the Cube to Your Scene
Once the mesh is created, you must add it to your Three.js scene so that the renderer knows to draw it.
// Add the cube to the scene
scene.add(cube);Complete Implementation Example
Here is how these steps fit into a standard, minimal Three.js boilerplate code, including a basic animation loop to rotate the cube:
import * as THREE from 'three';
// 1. Create the scene, camera, and renderer
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 2. Create the cube using BoxGeometry
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// Position the camera away from the center so we can see the cube
camera.position.z = 5;
// 3. Create an animation loop to render and rotate the cube
function animate() {
requestAnimationFrame(animate);
// Rotate the cube on the X and Y axes
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();