How to alter a ThreeJS Color using dat.gui

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

Oscar de la Hera Gomez
Written by Oscar de la Hera Gomez
First published on 11/16/2023 at 20:29
Last Updated on 11/16/2023 at 21:09
<p>Two flowers that represent ReactJS and ThreeJS side by side. Beneath them sits the text "dat.gui color."</p>

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

SubscribeReact, ThreeJS & GLSL Resources

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
View Repository

Step One: Setup the Project

<p>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.</p>

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.

How to use dat.gui with ReactJS and ThreeJS

Step Two: Create the Hex Color Type

<p>A screenshot of VSCode showing the color type</p>

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

Step Three: Create and Apply the Hex Color

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

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

<p>A screenshot of VSCode showing how we updated the setupGUI function. Code available below.</p>

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

<p>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.</p>

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.

Search our BlogReact, ThreeJS & GLSL Resources

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.
SubscribeContact UsVisit our BlogView our ServicesView our Work

Partner with us

We would love to get to know you and see how we can help your organization with its goals and needs.
Let's Talk

Stay Informed

Get occasional updates about our company, research, and product launches.
Subscribe