Rotating cube in Three.js
The rotating cube is the starting point of most Three.js projects: it shows how a scene, a camera, a mesh and a renderer fit together.
How it works
- Create the camera and scene. The code builds a
PerspectiveCamera, moves it back withcamera.position.z, and creates an emptyScene. It setsscene.backgroundso the cube stands out on a dark page. [1] - Build the cube mesh. A
BoxGeometrygives the shape andMeshNormalMaterialgives the material.new THREE.Mesh(geometry, material)combines them, andscene.add(mesh)puts the cube in the scene. [1] - Render and animate.
WebGLRendererdraws the scene into a canvas, which the code appends to the root element instead ofdocument.body.setAnimationLoop(animate)callsanimatewith a time value, and the cube's rotation is derived from it. [1]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import * as THREE from 'three';
const root = document.getElementById('root');
const width = root.clientWidth || 600, height = root.clientHeight || 380;
// init
const camera = new THREE.PerspectiveCamera(70, width / height, 0.01, 10);
camera.position.z = 1;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x111111);
const geometry = new THREE.BoxGeometry(0.4, 0.4, 0.4);
const material = new THREE.MeshNormalMaterial();
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(width, height);
renderer.setAnimationLoop(animate);
root.appendChild(renderer.domElement);
// animation
function animate(time) {
mesh.rotation.x = time / 2000;
mesh.rotation.y = time / 1000;
renderer.render(scene, camera);
}
Change the BoxGeometry sizes or the divisors in animate() to make the cube bigger or spin faster. Code written by AgentGid [1].
Change the BoxGeometry sizes or the divisors in animate() to make the cube bigger or spin faster. Code written by AgentGid [1].Checked Oct 12, 2026: it starts without errors in Chromium with three 0.186.1. Needs WebGL.
More Three.js examples
Animation loop in Three.js Built-in geometries in Three.js Lights and lit materials in Three.js Grouping objects in Three.js
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.