Three.js三大组件:场景(Scene)、相机(Camera)、渲染器(Renderer)
上一篇中我们学习了第一个Three.js场景"Hello World"。这一篇就来学习three.js的核心组件。
此图来源(Three.js中文网)
three.js的核心由三大组件构成:场景(Scene)、相机(Camera)和渲染器(Renderer)。下面我将详细介绍这三大件的作用和使用方法。
1. 场景(Scene)
场景是 Three.js 中所有 3D 对象的容器,相当于一个虚拟的 3D 世界。
基本特性:
-
是所有物体、灯光和相机的父容器
-
使用场景图结构管理对象
-
自动处理对象间的层级关系
创建场景:
// 创建3D场景对象Scene
const scene = new THREE.Scene();
常用属性:
/*若不为空,在渲染场景的时候将设置背景,且背景总是首先被渲染的。默认值为null*/
scene.background=...
/*设置背景的模糊度。仅影响分配给 Scene.background 的环境贴图。有效输入是介于 0 和 1 之间的浮点数。默认值为 0。*/
scene.backgroundBlurriness =...
/*如果不为空,它将强制场景中的每个物体使用这里的材质来渲染。默认值为null。*/
scene.overrideMaterial=...
常用方法:
scene.add(object); // 添加对象
scene.remove(object); // 移除对象
scene.children; // 获取所有子对象
2. 相机(Camera)
相机决定了场景中哪些部分会被渲染,相当于观察 3D 世界的"眼睛"。
常用相机类型:
- 透视相机(PerspectiveCamera) - 模拟人眼视角
const camera = new THREE.PerspectiveCamera(75, // 视野角度(FOV)window.innerWidth / window.innerHeight, // 宽高比0.1, // 近裁剪面1000 // 远裁剪面 );
- 正交相机(OrthographicCamera) - 无透视变形
const camera = new THREE.OrthographicCamera(width / -2, width / 2, // 左右平面height / 2, height / -2, // 上下平面1, // 近裁剪面1000 // 远裁剪面 );
相机位置和朝向:
camera.position.set(0, 0, 5); // 设置相机位置
camera.lookAt(0, 0, 0); // 设置相机看向的点
3. 渲染器(Renderer)
渲染器负责将场景和相机中的内容渲染到 HTML 页面上。
WebGL 渲染器(最常用):
const renderer = new THREE.WebGLRenderer({antialias: true, // 抗锯齿alpha: true // 透明背景
});
renderer.setSize(window.innerWidth, window.innerHeight); // 设置渲染尺寸
document.body.appendChild(renderer.domElement); // 添加到DOM
渲染器配置:
// 设置像素比(用于高清屏)
renderer.setPixelRatio(window.devicePixelRatio);// 开启阴影
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;// 设置色调映射
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1;
4.三大件协同工作示例
// 1. 创建场景
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x333333);// 2. 创建相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000
);
camera.position.z = 5;// 3. 创建渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);// 4. 创建物体并添加到场景
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
//添加
scene.add(cube);// 5. 渲染循环
function animate() {requestAnimationFrame(animate);cube.rotation.x += 0.01;cube.rotation.y += 0.01;renderer.render(scene, camera);
}
animate();
总结
-
Scene:3D 世界的容器,管理所有对象
-
Camera:决定观察视角和可见范围
-
Renderer:将 3D 场景渲染到 2D 屏幕上
这三大件构成了 Three.js 的基础架构,理解它们的关系和作用是学习 Three.js 的关键第一步。
如果文中有哪些问题,希望各位大佬轻喷。