Three.js is a JavaScript library that helps developers create interactive websites that are otherwise impossible to create with typical frontend frameworks. Three.js utilizes
When we create 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'll focus on the DirectionalLight
.
The DirectionalLight
constitutes parallel light rays being projected into the scene from a source infinitely far away. It is most commonly used to simulate daylight.
The syntax for initializing DirectionalLight
is as follows:
const light = new THREE.DirectionalLight(color, intensity);
The constructor for DirectionalLight
takes in two optional parameters:
color
: This is the hexadecimal color we want our DirectionalLight
to be. The default value is 0xffffff
.
intensity
: This is the strength of the light. The default value is
An example of a three.js scene where the objects inside are illuminated using DirectionalLight
is given below:
In the code shown above, we add two box shapes and some helpers inside the scene:
Line 36: We add OrbitControls
to the scene to allow the user to pan around it and view it from different angles.
Lines 39–42: We initialize our first box shape and store the returned object inside shape_one
. It is the red box placed at the center of the scene.
Lines 46–49: We initialize the second box shape and store the returned object inside shape_two
. This is the pink-colored shape placed behind the DirectionalLight
.
Lines 54–55: We initialize the DirectionalLight
and store the object returned by the constructor inside light
. We use the set
method to set its position
in the next line.
Note: Even though the
DirectionalLight
is positioned in front ofshape_two
, which is the pink-colored shape, it still illuminatesshape_two
. The reason is thatDirectionalLight
doesn't originate from a single point in the scene but instead from a point infinitely far away.
Line 60: We initialize the DirectionalLightHelper
and store the returned object inside helper
, which we add to the scene in the next line. This helps to visualize the DirectionalLight
.
Line 64: We initialize the AxesHelper
and store the returned object inside aHelper
. We also add that to the scene in the next line. This helps to visualize the axes and better understand where each object lies inside the scene.
Note: You can read more about the components being used in the scene in their respective Answers.
Free Resources