TExcelTAD
Home › 3D Web Games with Three.js › Renderer, Scene & Camera

Renderer, Scene & Camera

Every Three.js program has the same three objects at its heart:

  • a renderer, which owns the <canvas> and the WebGL context and draws pictures;
  • a scene, the root of a tree of objects (meshes, lights, groups) that make up your world;
  • a camera, the viewpoint the scene is drawn from.

One call puts them together: renderer.render(scene, camera). Everything else in Three.js feeds into that call.

The smallest scene

This program draws one frame and stops. There is no animation loop yet: the picture is drawn once and stays on the canvas.

html · try it yourself
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block }</style>
<script type="module">
import * as THREE from 'three';

// 1. Renderer: creates a <canvas> with a WebGL 2 context.
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);       // canvas size in CSS pixels
document.body.appendChild(renderer.domElement);  // domElement is the <canvas>

// 2. Scene: the root of everything we want to draw.
const scene = new THREE.Scene();
scene.background = new THREE.Color('#1d2333');

// 3. Camera: 50° vertical field of view, canvas aspect ratio, near and far planes.
const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 100);
camera.position.set(0, 1.5, 5);                  // up a little and back
camera.lookAt(0, 0, 0);                          // aim at the origin

// Something to look at, and light to see it by.
const box = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ color: '#ff8a50' }));
box.rotation.set(0.4, 0.6, 0);
scene.add(box);
const light = new THREE.DirectionalLight('#ffffff', 3);
light.position.set(2, 4, 3);
scene.add(light, new THREE.AmbientLight('#ffffff', 0.4));

renderer.render(scene, camera);                  // draw one frame
console.log('canvas', renderer.domElement.width, 'x', renderer.domElement.height, 'device pixels');
</script>

Things to notice:

  • renderer.domElement is an ordinary <canvas>. You can style it with CSS, put HTML on top of it (a HUD), or create the canvas yourself and pass it in: new THREE.WebGLRenderer({ canvas: myCanvas }).
  • setSize sets the canvas's CSS size and multiplies by the pixel ratio for its drawing buffer, which is why the console may print a size larger than the frame on a high-DPI screen. The Render Loop & Resizing explains why the ratio is capped at 2.
  • MeshStandardMaterial reacts to light. Without any light the box would be black; try deleting the two lights.

The coordinate system

Three.js is right-handed with Y up: +X points right, +Y points up, and +Z points toward the viewer. A camera that has not been rotated looks down −Z. Distances have no fixed unit, but physics engines, glTF and most tools assume 1 unit = 1 metre, so use metres.

AxesHelper draws the three axes in red (X), green (Y) and blue (Z), and GridHelper draws a floor grid. The camera below circles the origin slowly; watch the blue Z axis swing toward you and away again.

html · try it yourself
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block }</style>
<script type="module">
import * as THREE from 'three';

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

const scene = new THREE.Scene();
scene.background = new THREE.Color('#10131c');
scene.add(new THREE.GridHelper(10, 10, '#556', '#334'));   // 10 x 10 units, 1 unit per cell
scene.add(new THREE.AxesHelper(3));                         // X red, Y green, Z blue

// One sphere on each positive axis, coloured like the axis.
const ball = new THREE.SphereGeometry(0.2, 24, 16);
for (const [x, y, z, color] of [[3, 0, 0, 'red'], [0, 3, 0, 'lime'], [0, 0, 3, 'deepskyblue']]) {
  const m = new THREE.Mesh(ball, new THREE.MeshBasicMaterial({ color }));
  m.position.set(x, y, z);
  scene.add(m);
}

const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 100);
camera.position.set(6, 4, 8);
camera.lookAt(0, 0.8, 0);

renderer.setAnimationLoop((t) => {
  // Orbit the camera slowly around the Y axis so the 3D layout is easier to read.
  const a = t / 4000;
  camera.position.set(Math.sin(a) * 10, 5, Math.cos(a) * 10);
  camera.lookAt(0, 0.8, 0);
  renderer.render(scene, camera);
});
</script>

Tip: Keep an AxesHelper and a GridHelper in every new scene until it works. Most "I see nothing" bugs are a camera looking the wrong way or an object a thousand units away.

The camera's view

A PerspectiveCamera(fov, aspect, near, far) sees a frustum: a pyramid with its top cut off.

Parameter Meaning Typical values
fov vertical field of view in degrees 45–75 (first-person games often 70–90)
aspect width / height of the canvas innerWidth / innerHeight
near closest visible distance 0.1
far farthest visible distance 100–2000, as small as your world allows

Only things between near and far are drawn. Keep near as large and far as small as you can: depth-buffer precision is spread between them, and a tiny near (0.0001) causes z-fighting, where two close surfaces flicker through each other.

How much of the world fits on screen at a given distance follows from the field of view: the visible height is 2 · d · tan(fov / 2). This model prints it for a few distances and fields of view:

js · try it yourself
// Visible height and width of a perspective camera's view at distance d.
const aspect = 16 / 9;
function visibleSize(fovDeg, d) {
  const h = 2 * d * Math.tan((fovDeg * Math.PI / 180) / 2);
  return { h, w: h * aspect };
}

for (const fov of [45, 60, 75]) {
  const parts = [5, 10, 20].map((d) => {
    const { w, h } = visibleSize(fov, d);
    return `d=${String(d).padStart(2)}: ${w.toFixed(1)} x ${h.toFixed(1)}`;
  });
  console.log(`fov ${fov}°  ${parts.join('   ')}`);
}
fov 45°  d= 5: 7.4 x 4.1   d=10: 14.7 x 8.3   d=20: 29.5 x 16.6
fov 60°  d= 5: 10.3 x 5.8   d=10: 20.5 x 11.5   d=20: 41.1 x 23.1
fov 75°  d= 5: 13.6 x 7.7   d=10: 27.3 x 15.3   d=20: 54.6 x 30.7

So a 60° camera 10 m from a wall sees about 20 × 11.5 m of it on a 16:9 screen. That is handy when you place a camera to frame a level, and it is why a wider screen shows more on the sides (the vertical field of view is fixed, the horizontal one grows with aspect).

Output color space

The renderer converts the colors it computes into the color space of the screen. In r186, renderer.outputColorSpace is THREE.SRGBColorSpace by default, which is what you want for a normal canvas. Colors you write in code ('#ff8a50', 0xff8a50) are treated as sRGB and converted to linear values for lighting, then back for display, so they appear as you typed them under neutral light. The Color Spaces & Tone Mapping lesson explains the details; for now, leave the default alone.

Test yourself

An unrotated PerspectiveCamera at (0, 0, 5) looks in which direction?

  1. +Z
  2. −Z, toward the origin
  3. +Y
  4. −Y

You set camera.near = 0.00001 and far = 100000. What problem is likely?

  1. Nothing is drawn
  2. Z-fighting: distant surfaces flicker through each other because depth precision is spread too thin
  3. The frame rate halves
  4. Colors become washed out

A MeshStandardMaterial box renders completely black. What is the most likely cause?

  1. The camera is too far
  2. The scene has no lights (Standard materials need light)
  3. The renderer is not WebGL 2
  4. The box has no UVs