Please enable JavaScript to use CodeHS

Games & Animations with Three.js

Your First 3D Scene in Three.js

Build a spinning 3D cube in your browser and learn the four pieces every three.js program needs: a scene, a camera, a renderer, and a mesh. It is the same setup behind 3D games and websites, and it fits in one HTML file.

Part 1 of 12 ~12 min JavaScript
Part 1 of 12

What you'll learn

  • What three.js is, and why games and 3D websites use it.
  • The four building blocks of every three.js program: a scene, a camera, a renderer, and a mesh.
  • How to write a complete program that draws a spinning cube, and paste it into a plain HTML file.
  • How the animation loop makes things move, and how to change the cube's speed, color, and style live.

The Big Idea

A stage, an eye, a painter, and some actors

three.js is a JavaScript library, which means a big collection of ready-made code you can use in your own program. Its job is to draw 3D graphics inside a web browser. Under the hood it uses WebGL, a browser feature that lets your code talk to the GPU, the part of your computer built to draw millions of triangles every second. That is the same idea behind 3D games, product viewers, and those websites where a model floats and turns as you scroll.

The hard part of 3D is the math: figuring out how far away things are, which parts face the light, and how a 3D world should look when squashed onto a flat screen. three.js does that math for you. You describe the world, and it draws the picture.

Every three.js program, from a spinning cube to a full game, is built from the same four pieces. Think of a school play:

Scene

the stage

An empty container. Anything you want to see gets added to the scene, the way props and actors are placed on a stage.

Camera

the eye

One audience member's point of view. Where the camera sits and which way it faces decides what you see.

Renderer

the painter

Looks at the scene through the camera and paints one picture of it onto a <canvas> on your page. Each picture is a frame.

Mesh

an actor in costume

A geometry (the shape, like a box) wearing a material (the costume: color, shininess). Shape plus material equals a thing you can see.

There is one more piece you will meet in the code: lights. Just like stage lights, they are what make the actors visible. Without any light, most materials look completely black.

Simple definition: a three.js program builds a scene full of meshes, points a camera at it, and asks a renderer to paint what the camera sees, over and over, many times per second.


How It Works

The complete program

Here is the whole thing, split into three parts. Part 1 is the HTML file that holds it. Parts 2 and 3 are JavaScript that goes inside the <script type="module"> tag, one after the other. The program has two phases: set up the world once, then loop forever, turning the cube a tiny bit and painting a new frame each time.

1. The HTML shell

The importmap is a small note to the browser: "when my code asks for 'three', download it from this address." That is how three.js gets onto the page. There is no install step. Then a <div id="app"> gives the renderer somewhere to put its canvas.

index.html
<!DOCTYPE html>
<html>
<head>
  <style>
    body { margin: 0; background: #0b1220; }
    #app { width: 100vw; height: 100vh; }
  </style>
  <!-- Tell the browser where to download three.js from -->
  <script type="importmap">
  {
    "imports": {
      "three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js",
      "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"
    }
  }
  </script>
</head>
<body>
  <div id="app"></div>
  <script type="module">
    import * as THREE from 'three';

    // ... paste the code from scene.js and cube.js here ...
  </script>
</body>
</html>

The import * as THREE from 'three' line loads the library and names it THREE. Every three.js tool you use starts with that name.

2. The stage, the eye, the painter, and the lights

First we make an empty scene and give it a dark background. Next comes the camera. PerspectiveCamera works like a phone camera: things farther away look smaller. Its four numbers are the field of view (75 degrees, how wide the view is), the aspect ratio (width divided by height, so nothing looks stretched), and the near and far distances (anything closer than 0.1 or farther than 100 is not drawn). We move the camera to z = 3, three steps back from the center, so the cube is not sitting inside it.

Then the renderer. antialias: true smooths jagged edges. We size it to match the #app box and add its <canvas> to the page. Finally, two lights: an AmbientLight that glows evenly from everywhere, and a DirectionalLight that shines from one direction like the sun, so the cube's faces look different from each other.

scene.js
// 1. The scene is the stage. Everything you want to see goes in here.
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0b1220);

// 2. The camera is the eye: field of view, aspect ratio, near, far
const container = document.getElementById('app');
const camera = new THREE.PerspectiveCamera(
  75, container.clientWidth / container.clientHeight, 0.1, 100
);
camera.position.z = 3;   // step back so the cube is in front of us

// 3. The renderer is the painter. It draws onto a <canvas>.
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(container.clientWidth, container.clientHeight);
container.appendChild(renderer.domElement);

// 4. Lights. A MeshStandardMaterial is pitch black without them (more in Part 5).
const ambient = new THREE.AmbientLight(0xffffff, 1.5);
const sun = new THREE.DirectionalLight(0xffffff, 3);
sun.position.set(2, 3, 4);
scene.add(ambient, sun);

Colors like 0x0b1220 are the same six-digit hex colors you know from CSS (#0b1220), written with a 0x in front so JavaScript reads them as a number.

3. The cube and the animation loop

Now the actor. BoxGeometry(1, 1, 1) is a box that is 1 unit wide, tall, and deep. MeshStandardMaterial is a realistic material that reacts to light, and we give it a cyan color. A Mesh glues the shape and the material together, and scene.add(cube) puts it on stage.

Last, the part that makes it move. renderer.setAnimationLoop(animate) tells three.js: "run my animate function before every frame, about 60 times a second." Each time, we add 0.01 to the cube's rotation on two axes and paint a new frame. Lots of tiny turns, shown quickly, look like smooth spinning.

cube.js
// 5. A mesh is a shape (geometry) wearing a material (its costume)
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({ color: 0x4cc9f0 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

// 6. The animation loop: turn a tiny bit, paint a frame, repeat (about 60 times a second)
function animate() {
  cube.rotation.x += 0.01;   // 0.01 radians per frame
  cube.rotation.y += 0.01;
  renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);

This is exactly what the stages on this page are running, plus a few extra lines that pause the loop when a stage scrolls off screen.

One note about that 0.01. Rotation in three.js is measured in radians, not degrees. A full turn is about 6.28 radians, so 0.01 per frame is a very small turn, and at 60 frames per second the cube makes one full spin in about 10 seconds. You will learn radians properly in Part 6, and in Part 7 you will see why "per frame" is not quite the same as "per second."

How do I run this? Paste the HTML into a text editor, put the two JavaScript parts inside the <script type="module"> tag, save the file as index.html, and open it in a browser. The importmap address is what downloads three.js, so you need an internet connection the first time it loads.


Try It

Spin the cube

This stage is running the program you just read. Each control changes one number in that code, and the "live code" box under the controls shows you which line changed. Nothing here is faked: the slider really is the 0.01.

0.01
0x4cc9f0
Options material.wireframe and the loop
Live code
const material = new THREE.MeshStandardMaterial({ color: 0x4cc9f0 });
material.wireframe = false;
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
  1. Set the speed to 0. The cube stops, but notice it is still 3D: you can see three faces at once, each lit differently. The spinning was never what made it 3D. The camera and the lights did that.
  2. Drag the speed all the way to about 1.57. The cube almost freezes, and at 1.55 it looks like it is slowly spinning backward! A quarter turn is about 1.57 radians, and a cube looks the same after a quarter turn, so each frame lands almost exactly where the last one was. It is the same trick that makes wheels look like they roll backward in old movies.
  3. Turn on Wireframe and set the speed low. Now you can see the triangles the GPU actually draws. Count them on one face: there are 2. Every 3D shape, even a smooth sphere, is built out of triangles.

Watch Out

Common mistakes

Almost everyone hits one of these on their first scene. The good news is that each one has a quick fix.

Black screen

The page loads, the canvas is there, but it is completely empty. The camera is sitting at (0, 0, 0), which is the exact center of the cube. You are looking out from inside it.

Fix: move the camera back with camera.position.z = 3. If it still looks wrong, try 5 or 10 to see where the cube is.

Cube is solid black

You gave the material a bright color, but the cube shows up as a black silhouette. MeshStandardMaterial only shows color where light hits it, and there is no light in the scene.

Fix: add the AmbientLight and DirectionalLight from scene.js. To check the shape is really there, temporarily swap in MeshBasicMaterial, which ignores light completely.

Tiny or stretched canvas

The scene is squished into a small box, or the cube looks like a stretched rectangle. The renderer's size and the camera's aspect ratio do not match the container the canvas lives in.

Fix: give #app a real width and height in CSS, use those same numbers in renderer.setSize, and compute camera.aspect from them. If they change later, call camera.updateProjectionMatrix(). Part 2 covers this in detail.


Your Turn

Check your understanding

In your own words, what do the scene, the camera, and the renderer each do in a three.js program? Use the school-play analogy if it helps, and say why the cube would disappear if any one of them were missing.

Your answer:

Sample answer: the scene is the stage that holds everything, so without it the cube has nowhere to be. The camera is the eye that decides what part of the stage is in view, so without it there is no point of view to draw from. The renderer is the painter that takes what the camera sees and turns it into pixels on the canvas, so without it nothing ever reaches the screen. The cube itself is a mesh: a box shape wearing a cyan material.


Check Yourself

Quick quiz

1. Your cube shows up as a solid black shape even though you set color: 0x4cc9f0. What is the most likely cause?

2. What does renderer.render(scene, camera) actually do?

3. You change cube.rotation.y += 0.01 to cube.rotation.y += 0.02. What happens?

Keep learning

You have a spinning cube and you know what every line does. Next, look closer at the camera: where the x, y, and z axes point, what field of view really changes, and why the near and far numbers matter.

Part of the Games and Animations with Three.js tutorial series.