简体   繁体   English

如何在点击事件中动态添加颜色?

[英]How to add color on click event dynamically?

How to add color onclick event using three js? 如何使用三个js添加颜色onclick事件? 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. 您需要在onclick处理程序中为网格材料的color属性分配新的颜色。 For example, to make it red just add the following lines in your onclick handler - 例如,要使其变为红色,只需在onclick处理程序中添加以下几行-

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 - 在全局空间中声明可变mesh ,然后在函数中将其初始化,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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