简体   繁体   中英

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 );

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM