3

I'm new to Three Js and i do not know how to change the color of my material when i press a button on the html page. Do you have any suggestion? I'll attach here the code

here is how i declare 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
    });

here is how i update my color:

function render() {

renderer.render(scene, camera);
document.getElementById("colore").onclick= function(){
  console.log("prova caramella");
  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

 }

and lastly this is how i link 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;
//flower = dae;
scene.add(petali);
});
}

1 Answer 1

2

When updating the color, it's sufficient to do this:

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

There is no need to create a new material.

Besides, when using a latest version of three.js, it's not necessary to define the type for a uniform. The type is automatically derived from the compiled shader. On app level, it's sufficient to do.

uniforms: {
    p: { value: 2 },
    glowColor: { value: new THREE.Color(0x00ff00) }, 
},
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help it worked!! Have a nice day :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.