Rotating Cube in Three.js (Beginner Demo)

Beginner-friendly Three.js rotating cube example that teaches the core Scene, PerspectiveCamera, WebGLRenderer, mesh setup, and real-time animation loop used in most WebGL apps.

Key topics: three.js, rotating cube, basics

What this code does

- Scene Graph Basics: `THREE.Scene` is the root container for all objects, lights, and helpers rendered each frame.
- Camera Setup: `PerspectiveCamera(75, aspect, 0.1, 1000)` provides natural depth and is positioned so the cube stays in frame.
- Renderer Lifecycle: `WebGLRenderer` binds to the canvas, handles pixel ratio/size, and performs GPU draws every animation tick.
- Mesh Construction: `BoxGeometry` + `MeshStandardMaterial` defines both shape and physically based shading behavior.
- Lighting Fundamentals: a directional key light creates readable contrast, highlights, and depth cues on cube faces.
- Animation Loop Pattern: `requestAnimationFrame` updates rotation values over time and re-renders scene + camera continuously.
- Practical Extension Ideas: add OrbitControls, GUI sliders, or delta-time-based rotation to convert this into a reusable starter template.

Continue Learning

JavaScript Implementation

ES6+
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000)
camera.position.z = 3
const renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.setSize(width, height)
document.querySelector('#app').appendChild(renderer.domElement)
const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshStandardMaterial({ color: 0x00aaff })
const cube = new THREE.Mesh(geometry, material)
scene.add(cube)
const light = new THREE.DirectionalLight(0xffffff, 1)
light.position.set(2, 2, 2)
scene.add(light)

function animate () {
  requestAnimationFrame(animate)
  cube.rotation.x += 0.01
  cube.rotation.y += 0.01
  renderer.render(scene, camera)
}
animate()