Change the color of a specific object in three.js using the dat.GUI color picker

Is there a way to assign a color using dat.gui in a single object within Three.js?

I want to be able to select the color through a dialog box, similar to Box 3 in this example.

Any suggestions on how to achieve this?

Answer №1

I've created a custom function to incorporate color changing functionality using a color chooser:

function changeColor( object )
{
    var gui = new dat.GUI();

    var Configuration = function(){
            this.color = "#ffae23";
    }
    var config = new Configuration();

    var controller = gui.addColor( config, 'color');
    controller.onChange( function( colorValue  )
    {
      // The color value returned by the chooser is in the format: #ffff so
      // Remove the '#' and replace it with '0x'
      colorValue = colorValue.replace('#', '0x');
      // Create a Color object
      var colorObject = new THREE.Color(colorValue);
      // Set the color of the object
      object.material.color = colorObject;
    });
}

Answer №2

A more streamlined approach without unnecessary elements:

let userInterface = new dat.GUI();

let config = { selectedColor : '#ffae23' };    
userInterface.addColor(config, 'selectedColor').onChange( function(chosenColor) {
    object.material.color.set(chosenColor);
});

Answer №3

If you want to easily incorporate Three.js colors or uniform colors into dat.gui, here's a straightforward method:

dat.GUI.prototype.addThreeJSColor = function(obj, varName) {
    // To bridge the gap between three.js and dat.gui color formats, we use a dummy object as a middleman:
    var dummy = {};
    // Set an initial value for the dummy object:
    dummy[varName] = obj[varName].getStyle(); 
    return this.addColor(dummy, varName)
        .onChange(function(colorValue) {
            // Assign the chosen color to the original object:
            obj[varName].setStyle(colorValue);
        });
};
dat.GUI.prototype.addThreeJSUniformColor = function(material, uniformName, label) {
    return this.addThreeJSColor(material.uniforms[uniformName], "value").name(label || uniformName);
};

Answer №4

Forget about creating a whole new Three.Color instance. I'm not even sure if that's possible. Give the code snippet below a try - it did the trick for me.

function updateColor( element ) {
    var gui = new dat.GUI();

    var ColorSettings = function() {
        this.hex = "#ffae23";
    }
    
    var settings = new ColorSettings();
    
    var controller = gui.addColor(settings, 'hex');
    controller.onChange(function(colorValue) {
        // The color value returned by the picker will be like #ffff so
        // Remove the # and replace it with 0x
        colorValue = colorValue.replace('#', '0x');
        // Set the color in the object
        element.material.color.setHex(colorValue);
    });
}

Answer №5

Don't you think the example at is quite impressive?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When attempting to load a page in Mozilla, the initial DIV code fails to load

When trying to load a page in Mozilla, the first DIV code is not loading. I attempted to load HTML inside using: <div id="mainContent"></div> with the following call: if (destinationURL != null) { $.get(destinationURL, function(data) { ...

The use of `slot` attributes in Ionic has been deprecated and flagged by the eslint-plugin-vue

I encountered an error message while using VS Code: [vue/no-deprecated-slot-attribute] `slot` attributes are now considered deprecated. eslint-plugin-vue https://i.sstatic.net/DUMLN.png After installing two plugins in .eslintrc.js, I have the following c ...

Unlimited rotation - using setInterval function

I am encountering an issue with removing the move class from my code. Can someone please check it out for me? let lis = document.querySelectorAll('li') let arr = []; for (let i = 0; i < lis.length; i++) { arr.push(lis[i]); } setInterval( ...

Difficulty with Horizontal Mousewheel Scrolling

Struggling to implement a horizontal scrolling feature (via mousewheel) for both containers in the code below. I want this feature to be easily applied to any future container creations as well. <body> <style> #container { display: flex ...

How do I determine which radio button is currently selected within my Angular2 application?

In my HTML, I have the following radio buttons: <div class="col-lg-4" id="radioButtons"> <form action=""> <fieldset id="capacity"> <legend>capacity</legend> <label for="input-ao">< ...

What is the mechanism behind declaring a function using square brackets in Node.js/Javascript?

Encountering something new while working with Node.js - a unique way of declaring functions. You can find an example at this link. 'use strict'; const Actions = { ONE: 'one', TWO: 'two', THREE: 'three' }; clas ...

What is the best way to incorporate external JSON data into Jade for rendering from Express?

As someone new to Node / Express, I am interested in using Jade and Express to serve my static files. In the past, I have successfully used Jade with gulp-jade and gulp-data to render Jade files by utilizing JSON files with gulp-data for each page. Combi ...

Export data table from HTML to Excel successfully implemented with C#

I am currently working on an Umbraco website and developing a custom plugin for the backend that allows users to export an Excel worksheet from an HTML table. In order to achieve this functionality, I am utilizing AngularJS along with a C# controller. Belo ...

Utilizing Page Methods

I have encountered an issue while using an ajax callback for a void method. When I try to call another method within the calling method, I get an error. Any assistance with resolving this problem would be greatly appreciated. Here is the code snippet: ...

Efficiently sift through a vast assortment using a filtering method

Currently, I am developing an application similar to Uber which involves managing a collection of drivers with their current positions (latitude and longitude). One specific requirement is to find drivers who are within a 200-meter distance from the user& ...

Tips for aligning text in MUI Breadcrumbs

I am currently utilizing MUI Breadcrumb within my code and I am seeking a solution to center the content within the Breadcrumb. Below is the code snippet that I have attempted: https://i.stack.imgur.com/7zb1H.png <BreadcrumbStyle style={{marginTop:30}} ...

A guide to verifying a user's age using JavaScript by collecting information from 3 separate input fields

On page load, only the year input is required for users to fill in. The user can enter their birth year first without providing the month and day. Currently, I have a function that checks if a person is over 16 years old by comparing their birth year with ...

Block users from viewing the image displayed within a JavaScript canvas

On my server, I have a path to an image that is accessed by a JavaScript to load the image onto a canvas. The script then proceeds to hide certain parts of the image using black layers. The issue arises when a user can easily view my JavaScript code, extr ...

The AJAX function failed to trigger another JavaScript function after successfully completing its task

Trying to figure out how to execute a function after successful AJAX post request. The function I want to call is: function col() { var $container = $(".post-users-body"); $container.imagesLoaded(function() { $container.masonr ...

How I am able to access this.state in React without the need for binding or arrow functions

Understanding the concept of arrow functions inheriting the parent context is crucial in React development. Consider this React component example: import React, { Component } from 'react'; import { View, Text } from 'react-native'; i ...

Exploring the concept of inheritance in JavaScript and Angular programming

Currently, I am working on a project called "hello world" and it involves two HTML pages named "configuration.html" and "add configuration.html". Each page has its own controller defined as follows: angular.module('MissionControlApp').controller ...

What is the process for establishing destructured values?

I currently have the following code snippet: const { user, id, name, desc, photos, video, price, } = route.params; <ProductFooter selectedOptions={selectedOptions} {...route.params} /> Now I am looking ...

Is there a chart tool that allows for editing graphs by simply dragging points?

Currently, I am in search of a charting library that is preferably JavaScript-based (although Flash could work as well) and has the capability to display time series data as a line chart. Additionally, I need this library to allow users to drag points on t ...

Issue with CSV download box not showing up on Rails version 2.3.11

I've encountered an issue while trying to export a csv file with some data. I am using ajax call to select rows from the view table (jqGrid) and export them in a csv format. However, after a successful ajax call, the filtered data is displaying as an ...

The text does not change in the input field even with the .value method

I'm encountering an issue where I want to use .value to set the text of an input field. However, after setting the value of the input field, the text disappears when clicked on. I would like to find a solution where the text does not disappear upon cl ...