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

Configuring and Positioning Lights

Section 3

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

In the world of 3D, light is what allows us to perceive form, texture, and atmosphere. Without it, our scenes would be flat and lifeless. Three.js provides a variety of light types, each with its own characteristics and uses. In this section, we'll explore how to configure and position these lights to sculpt your 3D environments.

The most fundamental lights in Three.js are ambient and directional lights. Ambient light provides a soft, uniform illumination across the entire scene, preventing areas from being completely black. Directional lights simulate light coming from a distant source, like the sun, with parallel rays affecting all objects equally regardless of their position.

const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);

This code snippet creates an ambient light with a white color (0xffffff) and an intensity of 0.5. It's then added to the scene. Remember that ambient light is quite basic and doesn't cast shadows or create distinct highlights. It's primarily for setting a general base illumination.

const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(5, 5, 5);
scene.add(directionalLight);

Here, we've created a directional light, also white, with an intensity of 1. Crucially, we've used position.set(5, 5, 5) to define the direction from which the light emanates. In Three.js, a directional light's position determines its direction, not its location. The light will shine from this point towards the origin (0,0,0).

Beyond ambient and directional lights, we have point lights and spotlights. Point lights emit light in all directions from a single point, much like a bare light bulb. They're excellent for simulating localized light sources like lamps or candles. Spotlights, on the other hand, emit light in a cone shape, allowing for more focused illumination, similar to a stage spotlight.

const pointLight = new THREE.PointLight(0xff0000, 1, 10);
pointLight.position.set(-5, 0, 0);
scene.add(pointLight);
チャプターへ戻る