How to alter a ThreeJS Color using dat.gui

Oscar de la Hera Gomez
Two flowers that represent ReactJS and ThreeJS side by side. Beneath them sits the text "dat.gui color."

A step by step guide on using dat.gui to change a Three.Color via a hex color code.

The proposed solution can be found on the main branch of our Open Source React, Typescript & ViteJS Starter Project.

git clone git@github.com:delasign/reactjs-3js-vitejs-starter-project.git

Step One: Setup the Project

A screenshot of Chrome showing the shader on a plane and how the shader looks different thanks to the change in colors that we created using the GUI.

Follow the tutorial below to learn how to setup a Typescript & ViteJS project that works with a GLSL shader whose R, G, B color values can be adapted using dat.gui.

Step Two: Create the Hex Color Type

A screenshot of VSCode showing the color type

In the project, create a new Typescript type for the hex code.

Step Three: Create and Apply the Hex Color

A screenshot of VSCode demonstrating how we created a hex color and applied it to a ThreeJS Color. Code available below.

In the file that contains the scene, create a new hex color of the type declared in Step 2 and apply it to a shader or geometry using code similar to that found below.

attribute = new THREE.Color(color.hex)

Step Four: Update the GUI

A screenshot of VSCode showing how we updated the setupGUI function. Code available below.

Update the dat.gui to make use of a color which takes in the color declared in Step Three and through a listener applies it to a listener.

Sample code of how to do this is found below.

Step Five: Test

A screenshot of chrome showing how we can now alter the geometries color using a color picker that changes a hex code. The hex code's color matches the color of the geometry.

Run the app and confirm that you can dynamically change the color of the shader using a color picker.

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