shanmug kumar shanmug kumar - 3 months ago 22
Javascript Question

How to add color on click event dynamically?

How to add color onclick event using three js? Can anyone help? I have the below code:

var pts = [], numPts = 5;
for ( var i = 0; i < numPts * 2; i ++ ) {
var l = i % 2 == 1 ? 10 : 20;
var a = i / numPts * Math.PI;
pts.push( new THREE.Vector2 ( Math.cos( a ) * l, Math.sin( a ) * l ) );
}

var shape = new THREE.Shape( pts );
var geometry = new THREE.ExtrudeGeometry( shape, extrudeSettings );
var material2 = new THREE.MeshLambertMaterial( { color: 0x66CC00, wireframe: false } );
var mesh = new THREE.Mesh( geometry, material2 );
scene.add( mesh );

Answer

You need to assign a new color in the color property of the material of the mesh in your onclick handler. For example, to make it red just add the following lines in your onclick handler -

mesh.material.color = new THREE.Color(0xff0000);
mesh.material.needsUpdate = true;

Update:

Declare the variable mesh in global space then initiate it in the function like this -

var mesh;

function init() {

var pts = [], numPts = 5;
            for ( var i = 0; i < numPts * 2; i ++ ) {
                var l = i % 2 == 1 ? 10 : 20;
                var a = i / numPts * Math.PI;
                pts.push( new THREE.Vector2 ( Math.cos( a ) * l, Math.sin( a ) * l ) );
            }

            var shape = new THREE.Shape( pts );
            var geometry = new THREE.ExtrudeGeometry( shape, extrudeSettings );
            var material2 = new THREE.MeshLambertMaterial( { color: 0x66CC00, wireframe: false } );
            mesh = new THREE.Mesh( geometry, material2 );
            scene.add( mesh );
}