Changing the color of a Shader in ThreeJS: A guide

I am a beginner in Three Js and I am struggling with changing the color of my material when a button on the html page is pressed. Can anyone provide me with some suggestions? Below is the code snippet:

This is how I define my material:

  var color2= new THREE.Color(0xff0000)
  var customMaterial = new THREE.ShaderMaterial(
    {
      uniforms: {
        p: { type: "f", value: 2 },
        glowColor: { type: "c", value: color2 }, 
      },
      vertexShader: $('#vertexShader').text,
      fragmentShader: $('#fragmentShader').text,
      side: THREE.DoubleSide,
      blending: THREE.AdditiveBlending,   
      transparent: true,
      depthWrite: false
    });

This is how I update the color:

function render() {

renderer.render(scene, camera);
document.getElementById("colore").onclick= function(){
  console.log("testing color change");
  var customMaterial = new THREE.ShaderMaterial(
    {
      uniforms: {
        p: { type: "f", value: 2 },
        glowColor: { type: "c", value: new THREE.Color(0x00ff00) }, 
      },
      vertexShader: $('#vertexShader').text,
      fragmentShader: $('#fragmentShader').text,
      side: THREE.DoubleSide,
      blending: THREE.AdditiveBlending,   
      transparent: true,
      depthWrite: false
    });
    customMaterial.needsUpdate = true

 }

Finally, here is how I assign the material to my 3d model:

function petali2(){
var loaderpetali = new THREE.ColladaLoader();
loaderpetali.load('petali3.dae', function (collada) {
petali = collada.scene;
petali.traverse( function ( child ) {
  if (child instanceof THREE.Mesh) {
    console.log(child);
    child.material = customMaterial; 

  }
} );

petali.scale.x = 2;
petali.scale.y = 2;
petali.scale.z = 2;
scene.add(petali);
});
}

Answer №1

To change the color, simply follow this code snippet:

customMaterial.uniforms.glowColor.value.set( 0x00ff00 );

No need to create a new material, just update the existing one.

Additionally, in the latest version of three.js, you no longer have to specify the type for a uniform. The shader compiler automatically determines the type. At the application level, include the following:

uniforms: {
    p: { value: 2 },
    glowColor: { value: new THREE.Color(0x00ff00) }, 
},

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

Invoke Ajax utilizing an Identifier

How do I add an ID to Ajax: function callAjax() { jQuery.ajax({ type: "GET", url: "topics.php?action=details&id=", cache: false, success: function(res){ jQuery('#ajaxcontent').html(res) ...

Displaying a Jquery slider by clicking on links

I am interested in setting up a slider for two different forms. Specifically, I plan to have one form labeled Form 1 and another labeled Form 2 displayed as text. When users click on Form 1, a table containing the form will slide out from underneath the ...

if the arguments for a javascript function are not provided

Currently, I am in the process of learning JavaScript through a book called "Visual Quickstart Guide". However, I have encountered a challenge with understanding the logic behind a particular code snippet. In the function definition below, it appears that ...

Tips on altering the color of a circle's radius within Google Maps

I'm trying to add a circular radius on a Google Map. Even after reviewing the Google Maps API documentation, I'm still unsure of how to accomplish this task. Below is the code snippet I have been working with: const MyMapComponent = compose( ...

React error: "Unable to locate property 'bind' within the undefined"

After reviewing several solutions, I'm still struggling to understand. Below is my code snippet: // userInputActions.js ... export function dummy() { console.log('dummy function called'); } ... // *userInputPage.js* import * as use ...

Real-time updates using Express.js and Redis

Looking for guidance on managing real-time changes from Redis in Express.js. I am in need of fresh data from Redis every time there is an update. Can someone provide a helpful example or solution for this? ...

What is the process of redefining the toString method for a function?

I am currently tackling a coding challenge that involves chaining functions. While researching possible solutions online, I noticed that many of them involved using function.toString and overriding the toString method of a function to create a chained add ...

Struggling to vertically align elements within iron-pages

Struggling to vertically center the content within iron-pages (nested in a paper-drawer-panel). Check out the code snippet below: <paper-drawer-panel id="drawerPanel" responsive-width="1280px"> <div class="nav" drawer> <!-- Nav Conte ...

unable to properly assess the functionality of the timeout feature within the useEffect hook

I've been working on a lazyload image loader component that only loads images if they have been visible for more than 500ms. Although the functionality is working as expected, I'm facing challenges when it comes to writing a test to validate its ...

Loop through JSON array within an angular controller

I am currently attempting to iterate through a JSON array and display the values on the frontend of my application. I have provided my code, but I'm having trouble retrieving specific values (startDate, endDate) from within the array and displaying th ...

AngularJS - Click event failing to trigger controller function

I am currently honing my skills in Angularjs and Nodejs through working on a project. Following a helpful tutorial, I have structured my folders and configured my routes. Issue: I implemented a method called isActive to update ng-class when a tab is ...

Troubleshooting: Issues with Jquery's has, find, contains functions

As I check whether an element contains another element, I've previously utilized the jquery element.has(secondElement) function. In my angularjs project, I make use of jquery within a directive where I transclude elements through markup using ng-tran ...

Steps to develop a log-in API using Node.js

In the process of developing my web application, I have utilized node js exclusively for all functionalities and the web user interface has been successfully implemented. An issue that has come to light is that users are able to access the services API wi ...

I am currently facing an issue where the code provided in the Puppeteer documentation is not functioning correctly due to an Un

I followed the code example on the Puppeteer documentation website but unfortunately, it's not working for me. I have Puppeteer 3.0.0 installed via npm. const puppeteer = require('puppeteer'); (async () => { const browser = await pup ...

Leveraging webpack for CSS bundling

I'm currently working on bundling some NPM modules using webpack instead of utilizing a CDN. While I've successfully managed to integrate the .js files, I'm facing challenges with including the .css files for these modules. One example is ...

Is it possible to generate grid options dynamically for various tables within AngularJS using ui-grid?

I have developed a service for ui-grid table functionality. Currently, I am able to use this service on a single page but now I want to extend its usage to multiple pages, each with different table data. How can I pass grid options and JSON data for multip ...

Looking to establish a minimum height for a webpage

I am working on creating a webpage with three distinct sections: A fixed height header A fluid main section A fixed height footer My goal is to ensure that the page has a minimum height so that the bottom of the footer aligns with the bottom of the wind ...

Begin by executing the initial commit task with Git through Gulp, followed by performing the

I am currently working on a project and I am trying to use gulp to commit and push to git. However, I am encountering an issue where the push task is not waiting for the commit task to complete before running... Can anyone assist me with this? I want to s ...

A single pledge fulfilled in two distinct ways

My code ended up with a promise that raised some questions. Is it acceptable to resolve one condition with the token string value (resolve(token)), while resolving another condition with a promise of type Promise<string>: resolve(resultPromise); con ...

"Prevent users from taking screenshots by disabling the print screen key

Can someone help me figure out how to prevent users from taking a screenshot of my website by disabling the print screen key? Here's the code I've tried so far: <SCRIPT type="text/javascript"> focusInput = function() { document.focus() ...