[英]How to change the color of a cube with 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 );
幸运的是,我之前实现了一个解决方案 - 只要你不介意使用补间库(我使用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; }
});
}
请记住 ,小提琴的工作原因是因为我链接到两个外部库:
如果您有任何疑问,请给我发表评论,我一定会回答他们!
我已经更新了答案,包括使用单选按钮触发补间的功能。 重要的是,在创建网格时,实例化new THREE.Material()
而不是引用颜色数组中已有的材质。 像这样:
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]);
}
});
在前面的例子中,我使用了一个超轻量级补间插件( < 340 B
),不幸的是(我不知道)正在等待退役。 我已经更新了这个例子,使用了一个稍微更通用,更重的库GSAP - 它仍然是一个令人难以置信的能力和闪电般快速的库,所以我会毫不犹豫地使用它。
最后一次(希望如此),快乐的编码!
我发现材料的颜色可以直接调整!
var targetColor = new THREE.Color(0xafe2f3);
TweenMax.to( object.material.color, 2, {
r: targetColor.r,
g: targetColor.g,
b: targetColor.b
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.