Three.js 入门指南:从零开始创建3D网页应用
一、Three.js 简介:3D Web开发的革命性工具
Three.js 是一个基于 WebGL 的 JavaScript 3D 库,由 Ricardo Cabello(Mr.doob)于2010年创建。它通过封装复杂的 WebGL API,让开发者能够以更直观的方式创建和渲染3D场景。截至2025年,Three.js 已拥有超过 80,000+ 的 GitHub stars,成为 Web3D 开发的事实标准。
核心优势:
- 跨平台兼容性(支持所有现代浏览器)
- 丰富的内置几何体和材质
- 强大的动画系统
- 活跃的社区支持
二、环境搭建:5分钟快速启动
方案1:CDN引入(推荐初学者)
html
Three.js 基础示例
body { margin: 0; overflow: hidden; }
方案2:NPM安装(适合项目开发)
bash
npm install three
# 或
yarn add three
三、核心概念解析:Three.js的三大基石
1. 场景(Scene):3D世界的容器
javascript
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x333333); // 设置背景色
2. 相机(Camera):观察世界的视角
透视相机(PerspectiveCamera):模拟人眼视角
javascript
const camera = new THREE.PerspectiveCamera(
75, // 视野角度(FOV)
window.innerWidth / window.innerHeight, // 宽高比
0.1, // 近裁剪面
1000 // 远裁剪面
);
camera.position.z = 5; // 设置相机位置
正交相机(OrthographicCamera):2.5D视图常用
javascript
const orthoCamera = new THREE.OrthographicCamera(
window.innerWidth / -2,
window.innerWidth / 2,
window.innerHeight / 2,
window.innerHeight / -2,
0.1,
1000
);
3. 渲染器(Renderer):将场景绘制到画布
javascript
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
四、创建第一个3D对象:立方体入门
javascript
// 1. 创建几何体
const geometry = new THREE.BoxGeometry(1, 1, 1);
// 2. 创建材质
const material = new THREE.MeshBasicMaterial({
color: 0x00ff00,
wireframe: false // 设置为线框模式可查看结构
});
// 3. 创建网格对象(几何体+材质)
const cube = new THREE.Mesh(geometry, material);
// 4. 添加到场景
scene.add(cube);
// 动画循环
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
五、进阶功能实现
1. 光照系统
javascript
// 环境光
const ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);
// 平行光
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
directionalLight.position.set(1, 1, 1);
scene.add(directionalLight);
// 修改材质以响应光照
const phongMaterial = new THREE.MeshPhongMaterial({
color: 0x156289,
emissive: 0x072534,
side: THREE.DoubleSide,
flatShading: true
});
2. 纹理映射
javascript
const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load(\'path/to/texture.jpg\');
const texturedMaterial = new THREE.MeshBasicMaterial({
map: texture
});
3. 交互控制(使用OrbitControls)
javascript
import { OrbitControls } from \'three/examples/jsm/controls/OrbitControls.js\';
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // 添加阻尼效果
// 在动画循环中更新
function animate() {
controls.update();
// ...其他动画代码
}
六、性能优化实战技巧
1. 对象池技术
javascript
const cubePool = [];
const poolSize = 100;
// 初始化对象池
for (let i = 0; i < poolSize; i++) {
const cube = new THREE.Mesh(
new THREE.BoxGeometry(0.5, 0.5, 0.5),
new THREE.MeshBasicMaterial({ color: Math.random() * 0xffffff })
);
cube.visible = false;
scene.add(cube);
cubePool.push(cube);
}
// 从对象池获取对象
function getCube() {
for (const cube of cubePool) {
if (!cube.visible) {
cube.visible = true;
cube.position.set(
Math.random() * 10 - 5,
Math.random() * 10 - 5,
Math.random() * 10 - 5
);
return cube;
}
}
return null; // 池已满
}
2. 实例化渲染(InstancedMesh)
javascript
const geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
// 创建实例化网格(1000个立方体)
const count = 1000;
const instancedMesh = new THREE.InstancedMesh(geometry, material, count);
// 为每个实例设置位置
const matrix = new THREE.Matrix4();
for (let i = 0; i < count; i++) {
matrix.setPosition(
Math.random() * 20 - 10,
Math.random() * 20 - 10,
Math.random() * 20 - 10
);
instancedMesh.setMatrixAt(i, matrix);
}
scene.add(instancedMesh);
3. LOD(细节层次)技术
javascript
const lod = new THREE.LOD();
// 高精度模型(近距离显示)
const highGeo = new THREE.SphereGeometry(5, 64, 64);
const highMat = new THREE.MeshPhongMaterial({ color: 0xff0000 });
const highMesh = new THREE.Mesh(highGeo, highMat);
// 低精度模型(远距离显示)
const lowGeo = new THREE.SphereGeometry(5, 16, 16);
const lowMat = new THREE.MeshPhongMaterial({ color: 0x00ff00 });
const lowMesh = new THREE.Mesh(lowGeo, lowMat);
lod.addLevel(highMesh, 0); // 0单位距离内显示
lod.addLevel(lowMesh, 25); // 25单位距离外显示
scene.add(lod);
七、完整示例:可交互的3D场景
html
Three.js 完整示例
body { margin: 0; overflow: hidden; }
canvas { display: block; }
// 初始化场景、相机、渲染器
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x222222);
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 添加光源
const ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(1, 1, 1);
scene.add(directionalLight);
// 创建立方体
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshPhongMaterial({
color: 0x156289,
emissive: 0x072534,
flatShading: true
});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// 添加地面
const planeGeometry = new THREE.PlaneGeometry(20, 20);
const planeMaterial = new THREE.MeshStandardMaterial({
color: 0x666666,
roughness: 0.8,
metalness: 0.2
});
const plane = new THREE.Mesh(planeGeometry, planeMaterial);
plane.rotation.x = -Math.PI / 2;
scene.add(plane);
// 添加控制器
const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
// 窗口大小调整
window.addEventListener(\'resize\', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// 动画循环
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.005;
cube.rotation.y += 0.01;
controls.update();
renderer.render(scene, camera);
}
animate();
八、学习资源推荐
- 官方文档:threejs.org/docs
- 示例库:threejs.org/examples
- 书籍推荐:
- 《Three.js 入门指南》(2024版)
- 《WebGL与Three.js实战》
- 社区论坛:
- Stack Overflow (three.js标签)
- Three.js Discord 频道
九、未来趋势展望
- WebGPU集成:Three.js 正在逐步支持 WebGPU,预计性能提升3-5倍
- XR支持:增强对VR/AR设备的原生支持
- AI集成:与TensorFlow.js结合实现实时3D风格迁移
- 物理引擎升级:更真实的物理模拟(如与Cannon.js深度集成)
结语:Three.js 将复杂的3D渲染简化为可理解的组件系统,让Web开发者能够快速构建沉浸式体验。从简单的几何体到复杂的交互场景,掌握这三个核心概念(场景、相机、渲染器)就是打开3D Web开发大门的钥匙。建议从修改官方示例开始,逐步尝试添加光照、纹理和交互功能,最终实现自己的创意作品。