[英]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.