Warm tip: This article is reproduced from serverfault.com, please click

How to change Shader color in ThreeJS

发布于 2020-11-30 11:09:19

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);
});
}
Questioner
Lab Sintesi
Viewed
0
Mugen87 2020-11-30 20:09:12

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) }, 
},