Please enable JavaScript to use CodeHS

Games & Animations with Three.js

Lights and Shadows in Three.js

In Parts 1 and 4 the lights were just there. Now you own them: you set up a scene like a photo shoot with five kinds of light, then turn on real cast shadows and learn the four-line checklist that makes them finally appear.

Part 5 of 12 ~15 min JavaScript
Part 5 of 12

What you'll learn

  • Why nothing in three.js is lit until you add a light, and why a light is an object you add to the scene exactly like a mesh.
  • The five lights you will actually use, Ambient, Hemisphere, Directional, Point, and Spot, and the one-sentence job of each.
  • The four-step shadow checklist: the renderer, the light, the things that block light, and the floor they land on.
  • How to make shadows crisp instead of blurry or cut off, with shadow.mapSize, the shadow camera box, and soft shadow maps.

The Big Idea

Lights are objects, and shadows are earned

Here is the rule that trips up almost every beginner: in three.js, nothing is lit until you add a light. A brand-new scene is a pitch-black room. Put a MeshStandardMaterial sphere in it and you see nothing, because there is no light for the material to reflect. The only surfaces that show up in the dark are the ones from Part 4 that never asked about light in the first place: MeshBasicMaterial and MeshNormalMaterial.

The good news is that a light is not a hidden setting. It is an object, like a mesh. You build it with new, give it a position, and scene.add() it. You can move it in the animation loop, switch it off with visible = false, or attach it to the player as a flashlight. Lighting is the single biggest reason a 3D scene looks real instead of flat, and it is all just objects in your scene.

Think of setting up a photo shoot. There is the general glow of the room, so nothing is completely black. A window lets in sunlight from one direction, which is what gives faces their shape. A lamp throws warm light on whatever is near it. A flashlight makes a bright circle with a soft edge. Each of those is one three.js light type, and you mix them the way a photographer does: one to fill, one to shape, one or two for drama.

Shadows are the part students want most and struggle with most, because they are off by default and there is no single switch. Watch the hero stage: as the sun arcs over the set, the shadows stretch and sweep across the floor. Getting there takes four lines in four places, and if any one is missing you get no shadows and no error. This page hands you that checklist.

Simple definition: a light is an object that tells materials how bright to be and from which direction. Lights with a direction (directional, point, spot) can also cast shadows: three.js takes a picture of the scene from the light's point of view, called a shadow map, and anything the light could not see is drawn darker. Lights with no direction (ambient, hemisphere) cannot cast shadows, because there is nowhere for a shadow to fall.


How It Works

Lights, then shadows

We keep the setup from Part 1 (scene, camera, renderer, animation loop) and replace its lights with a proper set. The set is a gray floor with three amber objects on it: a cube, a sphere, and a torus knot. Every object wears a MeshStandardMaterial, so every one of them needs light to be seen.

1. The light menu

three.js has a handful of light types. Five of them cover nearly every game. Each card shows the constructor, and the first argument is always a color, so a warm bulb is as easy as 0xffb86b.

AmbientLight(color, intensity)

the room glow

The same light everywhere, from no direction. It keeps shadows from being pitch black. It cannot cast shadows and adds no shading, so too much of it makes everything look flat.

HemisphereLight(skyColor, groundColor, intensity)

sky above, bounce below

Sky color from above fading to ground color from below. Cheap, no shadows, and a much more natural outdoor fill than plain ambient: tops look sky-lit, undersides look like they bounce off dirt.

DirectionalLight(color, intensity)

the sun

Parallel rays, like sunlight. Its position only sets a direction: it shines from where it is toward its target, the origin by default. The workhorse for shadows.

PointLight(color, intensity, distance, decay)

a bulb

Shines in every direction from one spot and fades with distance. distance is where it reaches zero; decay stays at 2, the real-world falloff. A lamp, a torch, a glowing gem.

SpotLight(color, intensity, distance, angle, penumbra, decay)

a flashlight

A cone of light aimed at its target. angle is the cone's half-width in radians (keep it under Math.PI / 2); penumbra, from 0 to 1, softens the edge of the circle.

lights.js
// The room glow: everywhere at once, no direction, no shadows
const ambient = new THREE.AmbientLight(0xffffff, 0.4);

// Pale sky from above, warm dirt bounce from below
const hemi = new THREE.HemisphereLight(0xbfd4ff, 0x3b2a10, 0.6);

// The sun: position is a DIRECTION toward its target (the origin)
const sun = new THREE.DirectionalLight(0xffffff, 2.5);
sun.position.set(2.6, 6.6, 3.8);

// A warm bulb that fades out 12 units away
const point = new THREE.PointLight(0xffb86b, 30, 12, 2);
point.position.set(-3, 2.2, 1.5);

// A flashlight: cone half-width PI/7 (about 26 degrees), soft edge 0.4
const spot = new THREE.SpotLight(0xffffff, 60, 14, Math.PI / 7, 0.4, 2);
spot.position.set(3, 5, 2);

// Lights are objects. Add them like anything else.
scene.add(ambient, hemi, sun, point, spot);

Both stages on this page build exactly these five lights. The hero keeps only ambient and sun switched on and moves the sun in its animation loop; the "Try it" stage lets you switch each one with visible.

Why do these numbers look so big? In three.js r155 the point and spot lights switched to physically based units, like real light bulbs measured in candela. A bulb that used to be 1 is now closer to 30, and a spot closer to 60. If you copy an older tutorial and the room looks black, its intensities are from before the change: multiply the point and spot values by something like 20 to 50. Ambient, hemisphere, and directional lights kept their old scale.

2. Shadows: the four-step checklist

Shadows are off by default because they are expensive: for every shadow-casting light, three.js renders the scene a second time from the light's point of view into a shadow map, then checks every pixel against it. To turn them on you have to say yes in four places. Miss one and you get no shadows and no error message.

  1. The renderer: renderer.shadowMap.enabled = true. The master switch. This is the one people forget.
  2. The light: sun.castShadow = true. Only directional, point, and spot lights can do this.
  3. Every object that blocks light: cube.castShadow = true. Each mesh needs its own flag.
  4. Every surface shadows land on: ground.receiveShadow = true. An object can do both, so it shadows itself and its neighbors.
shadows.js
// 1. The renderer: the master switch (set it before the first render)
renderer.shadowMap.enabled = true;

// 2. The light: only directional, point, and spot lights can cast
sun.castShadow = true;
point.castShadow = true;
spot.castShadow = true;

// 3. The blockers: every mesh that should leave a shadow
cube.castShadow = true;
ball.castShadow = true;
knot.castShadow = true;

// 4. The floor: every surface a shadow can land on
ground.receiveShadow = true;

Four steps, four places. The "Shadows" button in the stage below flips steps 2 and 3 live. Step 1 stays on the whole time, for a reason explained in the live code.

3. Shadow quality

Once shadows appear, they are usually blurry, jagged, or chopped off, and three properties fix that. The shadow map is a square picture, and shadow.mapSize is its size in pixels, 512 by default. Bigger means crisper edges and a slower frame: 1024 is a good middle, 4096 is for a hero shot. The shadow "camera" that takes the picture is a real camera you can adjust. For a directional light it is orthographic, a box, and anything outside the box gets no shadow at all. The default box is only 10 units wide, which is why a big level's first shadow bug is a shadow that ends in a straight line. Set left, right, top, bottom, near, and far to cover your scene, then call updateProjectionMatrix(), the same rule as resizing in Part 2.

Finally, renderer.shadowMap.type picks how the map is sampled. THREE.PCFSoftShadowMap blends nearby pixels for soft edges; THREE.BasicShadowMap is fastest and shows every map pixel as a hard step. Thin dark stripes crawling across lit surfaces are shadow acne, and a tiny negative shadow.bias nudges them away.

shadow-quality.js
// Bigger map = crisper edges, slower frame. 512 is the default.
sun.shadow.mapSize.set(1024, 1024);

// A directional light's shadow camera is an orthographic BOX.
// Anything outside the box gets no shadow, so make it cover the scene.
const cam = sun.shadow.camera;
cam.left = -8;  cam.right = 8;
cam.top = 8;    cam.bottom = -8;
cam.near = 0.5; cam.far = 25;
cam.updateProjectionMatrix();   // same rule as resizing in Part 2

// Soft edges instead of hard pixel steps
renderer.shadowMap.type = THREE.PCFSoftShadowMap;

// Shadow acne (thin dark stripes)? A tiny negative bias clears it.
sun.shadow.bias = -0.0005;

// See the box: a wireframe of the shadow camera, great for debugging
const helper = new THREE.CameraHelper(sun.shadow.camera);
scene.add(helper);

The "Try it" stage runs all of this, with the helper hidden until you ask for it. Its map-size buttons swap 1024 for 256 or 4096 so you can see the trade-off on the sphere's shadow edge.


Try It

Light the set

The same set as the hero, with all five lights from lights.js. The light buttons flip each light's visible, so any mix is allowed, including none. The sun sliders move the directional light along an arc, and the shadow buttons run the lines from shadows.js and shadow-quality.js. Controls that do not apply right now are dimmed. The small orange dot is the point light's bulb.

Lights light.visible for each of the five lights; any mix is allowed
55°
35°
26°
Shadows castShadow on the lights and meshes
Shadow map size sun.shadow.mapSize, pixels per side
Debug CameraHelper(sun.shadow.camera) and a reset
Live code
ambient.visible = true;  hemi.visible = false;  sun.visible = true;
point.visible = false;  spot.visible = false;
sun.position.set(2.6, 6.6, 3.8);   // height 55°, angle 35°
sun.castShadow = true;  cube.castShadow = true;  ball.castShadow = true;  knot.castShadow = true;
// renderer.shadowMap.enabled stays true: flipping it live needs material.needsUpdate on every material
sun.shadow.mapSize.set(1024, 1024);
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
spot.angle = 0.45;   // radians: 26°
helper.visible = false;   // helper = new THREE.CameraHelper(sun.shadow.camera)
  1. Turn off Directional so only Ambient is on. The shadows vanish, and so does every hint of shape: the sphere becomes a flat amber disc and the cube a flat hexagon, because ambient light is the same from every direction. Now switch Ambient off too. Everything goes black except the unlit grid. That black scene is the default state of every three.js project, and it is why "my object is black" is almost always "I forgot a light."
  2. Directional back on, then drag Sun height down to 10. The shadows stretch into long streaks across the floor, like a real sunset, and the sides facing away from the sun go dark. Drag Sun angle all the way around and watch the shadows swing with it. That is what the arcing sun does in the hero stage, and it is a two-line day-night cycle for your own game.
  3. Click 256, then look at the edge of the sphere's shadow. It is a jagged staircase: the shadow map is only 256 pixels wide, so each pixel covers a chunk of floor. Click 4096 and the edge snaps sharp. Turn Soft edges off with 256 selected to see the raw pixel steps, then turn on Show shadow camera to see the box the sun takes its picture through.

Watch Out

Common mistakes

Lighting bugs almost never throw an error. They show up as no shadows, half a shadow, a washed-out white scene, or a light that seems to point the wrong way.

No shadows appear

You set castShadow on the light and the mesh and nothing changed. No error, no shadow.

Fix: walk the four-step checklist. Nine times out of ten the missing line is step 1, renderer.shadowMap.enabled = true. Then check that the floor has receiveShadow = true, and that the light is a directional, point, or spot light, since ambient and hemisphere lights cannot cast.

Shadows stop at a straight line

Shadows work near the middle of the level, but objects farther out cast nothing, and a long shadow gets chopped off along a razor-straight edge.

Fix: the directional light's shadow camera box is too small. Its default is 10 units wide. Set sun.shadow.camera.left/right/top/bottom (and far) to cover your scene, call updateProjectionMatrix(), and add a CameraHelper to see the box while you tune it.

Everything is washed-out white

Every surface is a blown-out pale blob, with no shading left to show its shape.

Fix: too much light. Either you scaled every intensity up after reading the r155 note (only point and spot lights changed units), or the ambient light is doing the directional light's job. Keep ambient around 0.3 to 0.6 and let one directional light provide the shape.

The light points the wrong way

You moved your DirectionalLight next to the player and expected it to light the player. It lit the middle of the level instead.

Fix: a directional light's position is a direction toward its target, not a spot in the room; the target is the origin by default. To aim it, set sun.target.position.set(x, y, z) and then scene.add(sun.target), which is required so the target's position updates. The same goes for a SpotLight.


Your Turn

Check your understanding

Your player casts a nice shadow on the ground, but the ground shows no shadows from the trees standing right next to the player. What is the most likely single line you forgot on the trees, and why does it have to go on each tree?

Your answer:

Sample answer: tree.castShadow = true, step 3 of the checklist. The player's shadow proves that steps 1, 2, and 4 are already done: the renderer has shadow maps on, the light casts, and the ground receives. What is left is the blocker itself. castShadow is a flag on each mesh, not on the scene, so every tree that should leave a shadow needs its own line (or a loop that sets it on all of them).


Check Yourself

Quick quiz

1. Which of these lights cannot cast a shadow, and why?

2. Which set of lines is the complete four-step checklist for shadows?

3. You change sun.shadow.mapSize from 1024 to 4096. What do you gain, and what does it cost?

Keep learning

You can now light a scene on purpose, pick the right light for the job, turn on shadows with the four-step checklist, and fix them when they are blurry or cut off. Next you take control of where things are: moving, spinning, and resizing objects, and nesting them so a moon can orbit a planet that orbits a sun.

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