TExcelTAD
Home › 3D Web Games with Three.js › Three.js Intro

Three.js Intro

Three.js is the most widely used JavaScript library for 3D graphics in the browser. It wraps WebGL (and, more and more, WebGPU) in a scene graph of cameras, meshes, lights and materials, so you write new THREE.Mesh(geometry, material) instead of hundreds of lines of buffer and shader setup. Games, product configurators, data visualisations and many award-winning websites are built on it.

This course teaches Three.js for games: not only how to draw a lit cube, but how to structure a game loop around a renderer, move a character, follow it with a camera, add physics, load models, keep the frame rate up on a phone, and ship. You will finish with a small 3D exploration game built step by step, and a second one as your mini project.

Try it now

Every scene in this course runs live inside the lesson. Click the scene below, then use WASD or the arrow keys to walk the orange explorer around the island and collect the five gems. Click outside the scene to pause.

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; overflow: hidden; background: #0e1018; }
  canvas { display: block; outline: none; touch-action: none; }
  #hud { position: fixed; left: 10px; top: 8px; color: #fff; font: 13px system-ui, sans-serif; pointer-events: none; text-shadow: 0 1px 2px #000; }
  #veil { position: fixed; inset: 0; display: grid; place-content: center; background: rgba(0, 0, 0, 0.55); color: #fff; font: 600 20px system-ui, sans-serif; text-align: center; pointer-events: none; }
  #veil small { display: block; margin-top: 6px; font-weight: 400; font-size: 13px; }
  #veil.off { display: none; }
</style>
<div id="hud"></div>
<div id="veil">Click to play<small>WASD or arrows to walk, collect the gems</small></div>
<script type="module">
import * as THREE from 'three';

// ---- 3D play kit: renderer, click to focus, keys, pause on blur, fixed-step loop ----
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.prepend(renderer.domElement);
const cv = renderer.domElement, veil = document.getElementById('veil');
const keys = new Set(), pressed = new Set();   // held now / pressed since the last update
let active = false, drawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; veil.classList.add('off'); });
cv.addEventListener('blur', () => { active = false; drawn = false; veil.classList.remove('off'); keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault();   // don't scroll the lesson
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function run(scene, camera, update) {
  const STEP = 1 / 60, timer = new THREE.Timer();
  let acc = 0;
  addEventListener('resize', () => {
    camera.aspect = innerWidth / innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(innerWidth, innerHeight);
    drawn = false;
  });
  renderer.setAnimationLoop((t) => {
    timer.update(t);
    if (active) {
      acc += Math.min(timer.getDelta(), 0.1);
      while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
    } else if (drawn) return;          // paused: the last frame stays on screen
    renderer.render(scene, camera);
    drawn = true;
  });
}
// ---- end of play kit ----

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x8ec5ff);
scene.fog = new THREE.Fog(0x8ec5ff, 18, 40);
const camera = new THREE.PerspectiveCamera(55, innerWidth / innerHeight, 0.1, 100);
scene.add(new THREE.HemisphereLight(0xdfefff, 0x4a6b3a, 1.6));
const sun = new THREE.DirectionalLight(0xffffff, 2.2);
sun.position.set(6, 10, 4);
scene.add(sun);

// The island: a flat cylinder of grass on a sandy base, plus a few trees.
const island = new THREE.Mesh(new THREE.CylinderGeometry(9, 10, 1, 40), new THREE.MeshStandardMaterial({ color: 0x5fa052 }));
island.position.y = -0.5;
scene.add(island);
const sea = new THREE.Mesh(new THREE.PlaneGeometry(200, 200), new THREE.MeshStandardMaterial({ color: 0x2d6fa8 }));
sea.rotation.x = -Math.PI / 2;
sea.position.y = -0.8;
scene.add(sea);
const trunkGeo = new THREE.CylinderGeometry(0.15, 0.2, 1);
const leafGeo = new THREE.ConeGeometry(0.8, 1.8, 7);
const trunkMat = new THREE.MeshStandardMaterial({ color: 0x7a5230 });
const leafMat = new THREE.MeshStandardMaterial({ color: 0x2f7d3b, flatShading: true });
for (const [x, z] of [[-5, -3], [4, -5], [6, 3], [-3, 5], [-6, 1]]) {
  const trunk = new THREE.Mesh(trunkGeo, trunkMat);
  trunk.position.set(x, 0.5, z);
  const leaves = new THREE.Mesh(leafGeo, leafMat);
  leaves.position.set(x, 1.8, z);
  scene.add(trunk, leaves);
}

// The player: a capsule with a "nose" so you can see which way it faces.
const player = new THREE.Group();
const body = new THREE.Mesh(new THREE.CapsuleGeometry(0.35, 0.6, 4, 12), new THREE.MeshStandardMaterial({ color: 0xff7043 }));
body.position.y = 0.65;
const nose = new THREE.Mesh(new THREE.BoxGeometry(0.2, 0.15, 0.3), new THREE.MeshStandardMaterial({ color: 0x222222 }));
nose.position.set(0, 0.9, 0.35);
player.add(body, nose);
scene.add(player);

// Gems: spinning octahedrons.
const gemGeo = new THREE.OctahedronGeometry(0.35);
const gemMat = new THREE.MeshStandardMaterial({ color: 0x66e0ff, emissive: 0x1a6680, metalness: 0.2, roughness: 0.3 });
const gems = [[3, 2], [-4, -1], [1, -6], [-2, 7], [7, -1]].map(([x, z]) => {
  const g = new THREE.Mesh(gemGeo, gemMat);
  g.position.set(x, 0.7, z);
  scene.add(g);
  return g;
});

const hud = document.getElementById('hud');
let found = 0, time = 0;
const camOffset = new THREE.Vector3(0, 5, 7);
camera.position.copy(camOffset);
camera.lookAt(0, 0.5, 0);

run(scene, camera, (dt) => {
  time += dt;
  const ix = (keys.has('KeyD') || keys.has('ArrowRight') ? 1 : 0) - (keys.has('KeyA') || keys.has('ArrowLeft') ? 1 : 0);
  const iz = (keys.has('KeyS') || keys.has('ArrowDown') ? 1 : 0) - (keys.has('KeyW') || keys.has('ArrowUp') ? 1 : 0);
  if (ix || iz) {
    const len = Math.hypot(ix, iz);
    player.position.x += (ix / len) * 5 * dt;
    player.position.z += (iz / len) * 5 * dt;
    player.rotation.y = Math.atan2(ix, iz);            // face the direction of travel
  }
  const r = Math.hypot(player.position.x, player.position.z);
  if (r > 8.6) player.position.multiplyScalar(8.6 / r);  // stay on the island
  for (const g of gems) {
    g.rotation.y += 2 * dt;
    if (g.visible && g.position.distanceTo(player.position.clone().setY(0.7)) < 0.8) { g.visible = false; found++; }
  }
  camera.position.lerp(player.position.clone().add(camOffset), 1 - Math.exp(-5 * dt));
  camera.lookAt(player.position.x, 0.5, player.position.z);
  hud.textContent = found < gems.length ? `Gems ${found} / ${gems.length}   ${time.toFixed(1)} s` : `All gems found in ${time.toFixed(1)} s!`;
});
</script>

That whole game is about 150 lines, and roughly a third of it is the play kit: the block between ---- 3D play kit and ---- end of play kit ---- that every playable scene in this course shares. It creates the renderer, takes keyboard focus when you click, stops the arrow keys from scrolling the lesson, pauses on blur and runs updates at a fixed 60 Hz. You will build each of those pieces yourself in the first lessons.

What Three.js gives you (and what it doesn't)

Three.js provides You (or another library) provide
Renderer for WebGL 2 (WebGLRenderer) and WebGPU (WebGPURenderer) The game loop's rules: input, state, win/lose
Scene graph: objects, groups, transforms, cameras Physics (cannon-es, Rapier)
Geometries, PBR materials, lights, shadows, fog Audio beyond the basics, UI frameworks
Loaders: glTF, textures, HDR, compressed textures An editor (there is a web editor, but no Unity-style one)
Animation system: clips, mixer, skinning, morph targets Networking, saving, menus
Raycasting, controls, post-processing (addons) Asset production (Blender, Substance, …)

Three.js is a rendering library, not a game engine. That is its strength (small, flexible, runs everywhere a browser does) and its cost: you assemble the engine parts yourself. This course shows you which parts are worth writing and which to take from a library.

Versions: r186

Three.js numbers its releases r150, r151, …; the npm package 0.186.1 is release r186, which this course and the site's playgrounds use. A new release comes out roughly every month, and releases may rename or remove APIs, so old tutorials often fail silently or look wrong. Three things changed recently enough to trip you up:

  • Color management is on by default: renderer.outputColorSpace is sRGB, and color textures must be marked with texture.colorSpace = THREE.SRGBColorSpace.
  • Physically based light units are the default since r155 (the legacy mode was removed later), so light intensities from older tutorials look too dark or too bright.
  • THREE.Timer replaces THREE.Clock, which is deprecated since r183.

Note: Always check which release a tutorial or Stack Overflow answer targets. If an example uses renderer.outputEncoding, THREE.Geometry or useLegacyLights, it predates the current API.

How a frame is made

You can print the moving parts without drawing anything. This plain-JavaScript model shows the order of work in one frame of a typical Three.js game (it runs here as is, with no WebGL):

js · try it yourself
// The order of work inside one animation-loop callback.
const log = [];
const input = { forward: true };
const player = { z: 0, speed: 4 };
let accumulator = 0;
const STEP = 1 / 60;

function frame(dtSeconds) {
  log.push(`frame dt=${dtSeconds.toFixed(4)}`);
  accumulator += dtSeconds;
  while (accumulator >= STEP) {                      // 1. fixed-step game update(s)
    if (input.forward) player.z -= player.speed * STEP;
    accumulator -= STEP;
    log.push(`  update -> z=${player.z.toFixed(3)}`);
  }
  log.push('  camera follows player');               // 2. camera after gameplay
  log.push('  renderer.render(scene, camera)');      // 3. draw once
}

frame(1 / 60);
frame(1 / 30);   // a slow frame runs two updates
console.log(log.join('\n'));
frame dt=0.0167
  update -> z=-0.067
  camera follows player
  renderer.render(scene, camera)
frame dt=0.0333
  update -> z=-0.133
  update -> z=-0.200
  camera follows player
  renderer.render(scene, camera)

If the loop ideas are new to you, the Game Development Fundamentals course explains them, and 2D Games with JavaScript & Canvas builds four complete games on the same loop.

Course map

Section You will learn
Basics renderer, scene, camera, meshes, the loop, resizing, custom geometry
Objects & Transforms position, rotation, quaternions, hierarchy, cameras
Materials & Lighting PBR materials, lights, shadows, textures, environment maps, color spaces
Assets glTF, compressed geometry and textures, loading screens
Interaction raycasting, orbit, first- and third-person controls
Animation clips and the mixer, skinned meshes, tweening
Physics cannon-es, Rapier, a character controller, triggers
Game: 3D Explorer a complete exploration game in four steps
Performance, Toolkit, Field Notes draw calls, instancing, LOD, React Three Fiber, debugging tools, builds, hard-won advice

You should be comfortable with modern JavaScript (modules, classes, arrow functions). The vector and matrix maths is explained as it comes up; Math for Games goes deeper.

Test yourself

Which statement best describes Three.js?

  1. A complete game engine with an editor, physics and networking
  2. A 3D rendering library with a scene graph, materials, loaders and animation, on top of WebGL/WebGPU
  3. A physics engine for the browser
  4. A browser plugin that must be installed

The npm package three@0.186.1 corresponds to which Three.js release?

  1. r18
  2. r186
  3. r1861
  4. v1.86

A tutorial sets renderer.outputEncoding = THREE.sRGBEncoding. What does that tell you?

  1. It is the recommended r186 setting
  2. It targets an older release; today you use renderer.outputColorSpace (sRGB by default)
  3. It enables HDR output
  4. It only applies to WebGPU