Three.js入门核心是先掌握三大基础要素,再逐步搭建完整3D场景,零基础也能快速跑通第一个可交互Demo。
🛠️ 开发环境快速搭建
推荐用Vite构建项目,无需复杂配置:
bashnpm create vite@latest three-demo --template vanillacd three-demonpm install threenpm run dev
也可以直接通过CDN引入,零构建工具快速上手:
html<scripttype="importmap">{"imports": {"three":"https://unpkg.com/three@0.170.0/build/three.module.js","three/addons/":"https://unpkg.com/three@0.170.0/examples/jsm/"}}</script>
🎯 三大核心基础概念
所有Three.js场景都围绕这三个对象构建:
Scene(场景):3D世界的容器,所有物体、灯光都要添加到其中才能被渲染
Camera(相机):决定观察场景的视角,最常用的是PerspectiveCamera透视相机,模拟人眼近大远小效果
Renderer(渲染器):将场景和相机的观察结果绘制到Canvas画布上,利用GPU硬件加速渲染
✨ 第一个旋转立方体完整代码
javascriptimport * as THREE from 'three';
// 1. 创建场景
const scene = new THREE.Scene();scene.background = new THREE.Color(0x222222);
// 2. 初始化透视相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);camera.position.z = 5;
// 3. 创建立方体网格
const geometry = new THREE.BoxGeometry(1, 1, 1);const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });const cube = new THREE.Mesh(geometry, material);scene.add(cube);
// 4. 添加基础光照
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);scene.add(ambientLight, directionalLight);
// 5. 初始化渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true });renderer.setSize(window.innerWidth, window.innerHeight);document.body.appendChild(renderer.domElement);
// 6. 启动动画循环
function animate() {requestAnimationFrame(animate);cube.rotation.x += 0.01;cube.rotation.y += 0.01;renderer.render(scene, camera);}animate();

