How to add lights to a material that uses a shader in ThreeJS

Oscar de la Hera Gomez
Two flowers that represent ReactJS and ThreeJS side by side. Beneath them sits the text "ReactJS & ThreeJS Lights (Shader Materials)."

A step by step guide on adding an ambient light to a scene in ThreeJS and learning how they adapt a material that uses a shader on a plane geometry in ReactJS.

We recommend that you clone our Open Source React-Redux Starter Project, checking out the tutorial/three-js/plane-shader branch and carrying out the steps below. The changes can be found on the tutorial/three-js/lights-shader-material branch.

git clone git@github.com:delasign/react-redux-starter-project.git

Step One: Setup the project

A screenshot of Chrome showing that the plane is now using the shader that we offer in this tutorial.

Follow the tutorial below to setup a responsive ThreeJS, ReactJS project that displays a plane in a scene which implements a material that uses a shader.

Step Two: Add the Light Source

A screenshot of VSCode showing how we added a light to the scene. Code available below.

Add a light to the scene using code similar to the one below.

Please note that it is strongly recommended that you use constants to define the color and position so that these variables can be passed onto the shader and be updated without causing errors due to inconsistent values.

Step Three: Set the Uniforms

A screenshot of VSCode showing how we set the uniforms for the shader.

Within the ShaderMaterial, add uniform values for the light color and position.

Step Four: Update the Vertex and Fragment Shader

A screenshot of VSCode showing the updated code for the vertex and fragment shaders. Code is available below.

Update the vertex and fragment shader to work with the light source.

Vertex Shader

Fragment Shader

If you are looking for a more advanced solution that implements standard GLSL files, please consult the guide below.

Step Five: Test

A screenshot of Chrome showing how the shader takes in the light source.

Run the code and confirm the light works as expected.

Looking to learn more about ReactJS and ThreeJS ?

Search our blog to find educational content on learning how to use ReactJS and ThreeJS.

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details