THREE.BoxGeometry
THREE.BoxGeometry 构建了诸如长方体和立方体之类的框。
立方体
使用 THREE.BoxGeometry 创建的多维数据集将对所有边使用相同的长度。
JavaScript 的
//Creates scene and camera
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
//Creates renderer and adds it to the DOM
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
//The Box!
//BoxGeometry (makes a geometry)
var geometry = new THREE.BoxGeometry( 1, 1, 1 );
//Material to apply to the cube (green)
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
//Applies material to BoxGeometry
var cube = new THREE.Mesh( geometry, material );
//Adds cube to the scene
scene.add( cube );
//Sets camera's distance away from cube (using this explanation only for simplicity's sake - in reality this actually sets the 'depth' of the camera's position)
camera.position.z = 5;
//Rendering
function render() {
requestAnimationFrame( render );
renderer.render( scene, camera );
}
render();
注意’render’功能。这使立方体每秒渲染 60 次。
完整代码(使用 HTML)
<!DOCTYPE html>
<html>
<head>
<title>THREE.BoxGeometry</title>
<script src="http://threejs.org/build/three.js"></script>
</head>
<body>
<script>
//Above JavaScript goes here
</script>
</body>
</html>
立方体
线 var geometry = new THREE.BoxGeometry( 1, 1, 1 );
给了我们一个立方体。要制作长方体,只需更改参数 - 它们分别定义立方体的长度,高度和深度。
例:
...
//Longer cuboid
var geometry = new THREE.BoxGeometry( 2, 1, 1 );
...
更多(证明立方体是三维的)
立方体似乎只是一个正方形。为了证明它是毫无疑问的三维,将以下代码行添加到’render’函数中:
...
cube.rotation.x += 0.05;
cube.rotation.y += 0.05;
...
看着旋转的立方体旋转着……圆形……圆形……
华美
不适合胆小的……
整个立方体的均匀颜色是……绿色。无聊。为了使每个面都成为不同的颜色,我们要挖掘几何体的面部。
var geometry = new THREE.BoxGeometry(3, 3, 3, 1, 1, 1);
/*Right of spawn face*/
geometry.faces[0].color = new THREE.Color(0xd9d9d9);
geometry.faces[1].color = new THREE.Color(0xd9d9d9);
/*Left of spawn face*/
geometry.faces[2].color = new THREE.Color(0x2196f3);
geometry.faces[3].color = new THREE.Color(0x2196f3);
/*Above spawn face*/
geometry.faces[4].color = new THREE.Color(0xffffff);
geometry.faces[5].color = new THREE.Color(0xffffff);
/*Below spawn face*/
geometry.faces[6].color = new THREE.Color(1, 0, 0);
geometry.faces[7].color = new THREE.Color(1, 0, 0);
/*Spawn face*/
geometry.faces[8].color = new THREE.Color(0, 1, 0);
geometry.faces[9].color = new THREE.Color(0, 1, 0);
/*Opposite spawn face*/
geometry.faces[10].color = new THREE.Color(0, 0, 1);
geometry.faces[11].color = new THREE.Color(0, 0, 1);
var material = new THREE.MeshBasicMaterial( {color: 0xffffff, vertexColors: THREE.FaceColors} );
var cube = new THREE.Mesh(geometry, material);
注意:对面部着色的方法不是最好的方法,但它运行良好(足够)。
笔记
HTML 文档正文中的 canvas
在哪里?
无需手动将 canvas
添加到身体。以下三行
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
创建渲染器,它的 canvas
并将 canvas
添加到 DOM。