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。