【问题标题】:Changing colours in three.js, a three js idiosyncrasy?在three.js 中更改颜色,三个js 特质?
【发布时间】:2017-10-07 05:03:11
【问题描述】:

我试图简单地将 three.js 中立方体的颜色更改为随机颜色,我已经搜索并引用了 Changing color of cube in three.js,但是即使控制台输出正确,我的代码也无法更改立方体颜色并手动设置颜色 eg(cube.material.color.setRGB(100,0,0);) 有效!我做错了什么?

var r = 1;
var g = 1;
var b = 1;

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

var geometry = new THREE.CubeGeometry(1,1,1);
var material = new THREE.MeshPhongMaterial();
var cube = new THREE.Mesh( geometry, material );

scene.add( cube );

var directionalLight = new THREE.DirectionalLight( 'white', 1 );
directionalLight.position.set( 1, 0, 1 );
scene.add( directionalLight );

camera.position.z = 5;

r = Math.round(Math.random() * (255 - 0) + 0);
g = Math.round(Math.random() * (255 - 0) + 0);
b = Math.round(Math.random() * (255 - 0) + 0);


/* issue, the below console output is correct however the colour is not set. Setting the colour values manually works!! */

console.log(r,g,b);
cube.material.color.setRGB(r,g,b);

function render() {

    requestAnimationFrame(render);
    renderer.render(scene, camera);

    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    //cube.position.z += 0.01;



}
render();

【问题讨论】:

    标签: javascript three.js


    【解决方案1】:

    当使用setRGB( r, g, b ) 方法设置THREE.Color 时,rgb 取值介于 0 和 1 之间。

    color.setRGB( Math.random(), Math.random(), Math.random() );
    

    http://threejs.org/docs/#api/math/Color

    three.js r.85

    【讨论】:

    • 欢迎来到 SO。请记住通过单击复选标记“接受”答案。谢谢。
    猜你喜欢
    • 2015-04-17
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 2016-08-27
    • 2013-06-03
    • 2019-05-30
    相关资源
    最近更新 更多