Hello Cube
Hello Cube
在
- 相机:决定哪些东西将要在屏幕上渲染。
- 光源:它们会对材质如何显示,以及生成阴影时材质如何使用产生影响。
- 物体:它们是在相机透视图里的渲染对象:方块、球体等。

// Online Demo: https://codepen.io/pen/?&editable=true&editors=101=https%3A%2F%2Fthreejsfundamentals.org%2F
import * as THREE from "https://threejsfundamentals.org/threejs/resources/threejs/r119/build/three.module.js";
function main() {
const canvas = document.querySelector("#c");
const renderer = new THREE.WebGLRenderer({ canvas });
const fov = 75;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 5;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 2;
const scene = new THREE.Scene();
{
const color = 0xffffff;
const intensity = 1;
const light = new THREE.DirectionalLight(color, intensity);
light.position.set(-1, 2, 4);
scene.add(light);
}
const boxWidth = 1;
const boxHeight = 1;
const boxDepth = 1;
const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
const material = new THREE.MeshPhongMaterial({ color: 0x44aa88 }); // greenish blue
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
function render(time) {
time *= 0.001; // convert time to seconds
cube.rotation.x = time;
cube.rotation.y = time;
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
main();
相机
这里对于相机的位置进行简要分析:
fov 是field of view 的缩写。当前的情况是垂直方向为75 度。注意three.js 中大多数的角用弧度表示,但是因为某些原因透视摄像机使用角度表示。aspect 指canvas 的显示比例。但是在默认情况下canvas 是300x150 像素,所以aspect 为300/150 或者说2. 。near 和far 代表摄像机前方将要被渲染的空间。任何在这个范围前面或者后面的物体都将被裁剪( 不绘制) 。
这四个参数定义了一个 “frustum”(译者注:视椎体
摄像机默认指向

上面的示意图中我们能看到摄像机的位置在
动画
我们来让立方体旋转起来,希望 能看出是三维的。为了让它动起来我们需要在渲染循环函数中使用
function render(time) {
time *= 0.001; // convert time to seconds
cube.rotation.x = time;
cube.rotation.y = time;
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
灯光
效果好了一些但还是很难看出是三维的。添加灯光会有帮助,所以我们来添加一盏灯光。
{
const color = 0xffffff;
const intensity = 1;
const light = new THREE.DirectionalLight(color, intensity);
light.position.set(-1, 2, 4);
scene.add(light);
}
平行光有一个位置和目标点。默认值都为
- const material = new THREE.MeshBasicMaterial({color: 0x44aa88}); // greenish blue
+ const material = new THREE.MeshPhongMaterial({color: 0x44aa88}); // greenish blue

多个立方体
为了更有乐趣我们再添加两个立方体。每个立方体将会使用同一个几何体但是不同的材质,这样每个立方体将会是不同的颜色。首先我们创建一个根据指定的颜色生成新材质的函数。然后函数会根据指定的几何体生成一个
function makeInstance(geometry, color, x) {
const material = new THREE.MeshPhongMaterial({ color });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
cube.position.x = x;
return cube;
}
然后我们将使用三种不同的颜色和
const cubes = [
makeInstance(geometry, 0x44aa88, 0),
makeInstance(geometry, 0x8844aa, -2),
makeInstance(geometry, 0xaa8844, 2),
];
最后我们将在渲染函数中旋转三个立方体。我们 给每个立方体设置了稍微不同的旋转角度。
function render(time) {
time *= 0.001; // convert time to seconds
cubes.forEach((cube, ndx) => {
const speed = 1 + ndx * .1;
const rot = time * speed;
cube.rotation.x = rot;
cube.rotation.y = rot;
});
...