Three.js for Creators: A Beginner's Guide to 3D Web Experiences

Enabling and Configuring Shadows

Section 6

Chapter 4: Bringing it to Life: Lighting and Shadows

Three.js for Creators: A Beginner's Guide to 3D Web ExperiencesChapter 4: Bringing it to Life: Lighting and Shadows

Shadows are a fundamental aspect of realism in 3D graphics. They add depth, volume, and a sense of the environment. In Three.js, enabling and configuring shadows involves a few key steps. It's not as simple as flipping a switch; it requires careful consideration of your scene's lights and the objects that cast and receive shadows.

The first crucial step is to enable shadows for the renderer. This tells Three.js that we intend to render shadows. You do this by accessing the shadowMap property of your WebGLRenderer and setting its enabled property to true.

const renderer = new THREE.WebGLRenderer();
renderer.shadowMap.enabled = true;

Not all lights in Three.js can cast shadows. The most common light types that support shadows are DirectionalLight and SpotLight. PointLight can also cast shadows, but it's often more computationally expensive. To make a light cast shadows, you need to explicitly enable this capability for that specific light.

const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.castShadow = true;

Similarly, not all objects will automatically cast or receive shadows. You need to tell each mesh whether it should participate in the shadow rendering process. You do this by setting the castShadow and receiveShadow properties on the Mesh object itself.

const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
const cubeMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000 });
const cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
cube.castShadow = true;
cube.receiveShadow = true;

const groundGeometry = new THREE.PlaneGeometry(10, 10);
const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.receiveShadow = true;
scene.add(cube, ground);

When a light casts shadows, it needs to 'render' the scene from its perspective to generate a shadow map. This process has parameters that can significantly impact the quality and performance of your shadows. The most important are related to the shadow property of the light.

チャプターへ戻る