What is SpotLight in three.js?
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.
How it works
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.
Syntax
The syntax for initializing the SpotLight is mentioned below:
const light = new THREE.SpotLight(color, intensity, distance, angle, penumbra, decay);
Parameters
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 is0xffffff.intensity: This parameter is of typefloatand 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 typefloatand defaults to. This means there's no limit on the distance that the light can reach. angle: The angle at which the light diverges from its origin. It is of typeNumberand is given in radians. The upper bound on this value isMath.PI/2which is equivalent to. penumbra: This is the diffusion of the light towards the outer edges. It is of typefloatand ranges fromto . decay: This is of typefloatand dictates the amount by which the light intensity decreases as the distance increases.
Example
The example below illustrates the use of SpotLight in a scene.
Explanation
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
OrbitControlsto 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 theSpotLight.Lines 45–48: We create
shape_two, which is placed behind theSpotLightand is not illuminated.Lines 53–54: Here, we initialize the
SpotLightwith the default parameters and add it to the scene.Line 59: Here, we initialize a
SpotLightHelperto help visualize theSpotLight.Line 63: We initialize
AxesHelper. This is to help visualize the axes and better understand where each object lies inside the scene.
Free Resources