如何使用Three.js更改多维数据集的颜色

时间:2015-08-27 14:31:46

标签: javascript jquery three.js

我想根据单选按钮选择更改多维数据集的颜色。如何通过平稳过渡实现这一目标?

单选按钮

<input id="black" type="radio" data-color="black" name="color" value="" checked="checked">
<input id="white" type="radio" data-color="white" name="color" value="">
<input id="blue" type="radio" data-color="chamois" name="color" value="">

材料

var color = {

    "black": new THREE.MeshPhongMaterial({
        color: 0x222222
    }),
    "white": new THREE.MeshPhongMaterial({
        color: 0xffffff
    }),
    "chamois": new THREE.MeshPhongMaterial({
        color: 0xEDE6D4
    })

}

几何

var geometry= new THREE.BoxGeometry(2,2,2);
var mesh = new THREE.Mesh(geometry, color [ "black" ]);
scene.add(mesh );

2 个答案:

答案 0 :(得分:5)

幸运的是,我之前实现了一个解决方案 - 只要您不介意使用补间库(我使用GSAP),这段代码效果很好。

这里只是补色代码(为简洁起见):

function colorTo (target, value){
    var target = scene.getObjectByName(target);
    var initial = new THREE.Color(target.material.color.getHex());
    var value = new THREE.Color(value.color.getHex());

    TweenLite.to(initial, 1, {     //This syntax is relevant to GSAP's TweenLite, I'll provide a link to the docs
        r: value.r,
        g: value.g,
        b: value.b,
        ease: Cubic.easeInOut,
        onUpdate: function() { target.material.color = initial; }
    });
}

Link to full code in fiddle

记住,小提琴之所以起作用的原因是因为我链接到两个外部库:

  1. three.min.js
  2. TweenMax.min.js
  3. 如果您有任何问题,请发表评论,我一定会回答!

    Link to the GSAP TweenLite docs

    修改

    我已经更新了答案,包括使用单选按钮触发补间的功能。重要的是,在创建网格时,实例化new THREE.Material() 而不是引用 color 数组中已有的材质。像这样:

    var mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ color: 0x222222})); 
    

    然后将它连接到无线电控件根本没问题:

    $("#inputs input").change(function(event){
        if ($(this).prop("checked")) {
            var targetColor = $(this).data("color");
            colorTo("box", color[targetColor]);
        }
    });
    

    编辑2

    在上一个例子中,我使用了一个超轻量级补间插件(< 340 B),不幸的是(我不知道)正在等待退役。我已经更新了这个例子,使用了一个稍微更通用,更重的库GSAP - 它仍然是一个令人难以置信的能力和闪电般快速的库,所以我会毫不犹豫地使用它。

    最后一次(希望如此),快乐的编码!

答案 1 :(得分:2)

我发现材料的颜色可以直接补发!

var targetColor = new THREE.Color(0xafe2f3);
TweenMax.to( object.material.color, 2, {
                r: targetColor.r,
                g: targetColor.g,
                b: targetColor.b
});
相关问题