如何在单击时更改使用JSONLoader创建的对象的颜色

时间:2022-03-17 19:35:04

I've started working with Three.js recently and created an object using the JSONLoader. The whole object contains a material with a grey color.

我最近开始使用Three.js并使用JSONLoader创建了一个对象。整个对象包含一种灰色的材质。

Now i just want to be able to change a color of the object by clicking on a button I've added to my HTML.

现在我只想通过单击我添加到HTML中的按钮来更改对象的颜色。

<input type="button" value="Change Color" onClick="group.material.color.setHex('0xffffff')">

DevTools delivers following message:

DevTools提供以下消息:

Cannot read property 'color' of undefined

无法读取未定义的属性“颜色”

Well, I checked if the object contains the property color and of course it doesn't.

好吧,我检查了对象是否包含属性颜色,当然它没有。

I knew it wouldn't work, but the hope dies last. Here is the part where the object is getting created:

我知道它不起作用,但希望终于消失了。以下是创建对象的部分:

group = new THREE.Object3D();

    //load mesh 
    var loader = new THREE.JSONLoader();
    loader.load('models/s_class.js',  function( geometry ) {
        mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial( {color: 0x2f3a4c}) );
        mesh.scale.set( 10, 10, 10 );
        mesh.rotation.x = -Math.PI / 2;
        mesh.position.y = 0;
        group.add( mesh );
        scene.add( group );
    } );

Please, is there ANY way to simply change a color by pressing a button? Do I have to build my object with another Loader maybe?

请问,有什么方法可以通过按下按钮来简单地改变颜色吗?我是否必须使用另一台Loader构建我的对象?

Here is my code on jsfiddle

这是我在jsfiddle上的代码

Thanks in advance!!!

提前致谢!!!

1 个解决方案

#1


0  

Don't set the color of the "group", but the children. E.g. use the traverse function.

不要设置“组”的颜色,而是设置孩子的颜色。例如。使用遍历功能。

 group.traverse(function(child) {
    if(child instanceof THREE.Mesh){
          child.material.color.setHex('0xffffff');
    }
 });

#1


0  

Don't set the color of the "group", but the children. E.g. use the traverse function.

不要设置“组”的颜色,而是设置孩子的颜色。例如。使用遍历功能。

 group.traverse(function(child) {
    if(child instanceof THREE.Mesh){
          child.material.color.setHex('0xffffff');
    }
 });