Three.js is a JavaScript library developers use to render graphics on their websites and create interactive pages. Three.js utilizes
When creating a scene in three.js, it is essential to use proper lighting to illuminate the objects inside the scene. Three.js offers different types of lights. In this Answer, we will focus on SpotLight
.
In three.js, SpotLight
unlike DirectionalLight
, gets emitted from a single point. The light emitted from the point diverges as the distance from the point increases.
The syntax for initializing the SpotLight
is mentioned below:
const light = new THREE.SpotLight(color, intensity, distance, angle, penumbra, decay);
The constructor for SpotLight
takes the following parameters:
color
: This is a hexadecimal value of the color we want our light to be. It is optional, and the default value is 0xffffff
.
intensity
: This parameter is of type float
and dictates the strength or intensity of the light. It is also optional, and the default value is
distance
: This is the maximum range of the light. It is of type float
and defaults to
angle
: The angle at which the light diverges from its origin. It is of type Number
and is given in radians. The upper bound on this value is Math.PI/2
which is equivalent to
penumbra
: This is the diffusion of the light towards the outer edges. It is of type float
and ranges from
decay
: This is of type float
and dictates the amount by which the light intensity decreases as the distance increases.
The example below illustrates the use of SpotLight
in a scene.
In the scene above, we add two shapes inside the scene. One is illuminated by the SpotLight
, whereas the other one, positioned behind the SpotLight
, is not. This phenomenon does not work with DirectionalLight
.
Line 35: Here, we add OrbitControls
to the scene so the user can pan around and view it from different angles.
Lines 38–41: We create shape_one
, the red-colored box illuminated by the SpotLight
.
Lines 45–48: We create shape_two
, which is placed behind the SpotLight
and is not illuminated.
Lines 53–54: Here, we initialize the SpotLight
with the default parameters and add it to the scene.
Line 59: Here, we initialize a SpotLightHelper
to help visualize the SpotLight
.
Line 63: We initialize AxesHelper
. This is to help visualize the axes and better understand where each object lies inside the scene.
Free Resources