现在位置: 首页 > Three.js 教程 > 正文

Three.js 环境搭建

Three.js 对环境的要求出奇地低:一个现代浏览器加一个顺手的编辑器,就能开发所有本教程的示例。

本章把两种引入方式(快速原型用的 importmap、正式项目用的 npm + Vite)都跑通,装好三个调试工具,最后配置好 AI 开发环境。


Three.js 安装与引入

Three.js 主要有两种常见使用方式:通过 npm 安装到前端项目,或者使用 CDN 和 Import Map 在普通 HTML 页面中引入。

使用 npm 安装

如果我们使用 Vite、Vue 或其他现代前端开发环境,可以执行:

npm install three

随后在 JavaScript 模块中使用:

import * as THREE from 'three';

通过 CDN 引入

Three.js 可以通过 CDN 直接引入,无需安装 Node.js 或构建工具。

如果只想快速学习,我们可以直接创建一个 HTML 文件,通过 importmap 指定 Three.js 的模块地址。

CDN 引入地址
jsDelivr https://cdn.jsdelivr.net/npm/three@0.187.0/build/three.module.js
Cloudflare cdnjs https://cdnjs.cloudflare.com/ajax/libs/three.js/0.187.0/three.module.js
UNPKG https://unpkg.com/three@0.187.0/build/three.module.js
esm.sh https://esm.sh/three@0.187.0

我们可以使用 Import Map 指定 Three.js 的加载地址:

<script type="importmap">
{
  "imports": {
    "three": "https://cdn.jsdelivr.net/npm/three@0.187.0/build/three.module.js",
    "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.187.0/examples/jsm/"
  }
}
</script>

<script type="module">
import * as THREE from 'three';

const scene = new THREE.Scene();
console.log(scene);
</script>

三分钟跑起来:importmap 引入

Three.js 从 r160 起只以 ES Module 形式发布,不再提供全局脚本版。这意味着以前那种一行 <script src="three.min.js"> 的引入方式已经彻底作废——如果你在旧教程或 AI 生成的代码里看到它,那段代码必然跑不起来。现在官方推荐的免构建方案是 importmap:

Three.js 实例:importmap 最小模板

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Three.js 最小模板</title>
<style>
  body { margin: 0; overflow: hidden; }
</style>
<script type="importmap">
{
  "imports": {
    "three": "https://static.jyshare.com/assets/libs/threejs/three-0.187.0/build/three.module.js",
    "three/addons/": "https://static.jyshare.com/assets/libs/threejs/three-0.187.0/examples/jsm/"
  }
}
</script>
</head>
<body>
<script type="module">
import * as THREE from 'three';

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x1a1a2e);

const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 100);
camera.position.set(3, 2, 4);
camera.lookAt(0, 0, 0);

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);

const cube = new THREE.Mesh(
  new THREE.BoxGeometry(1, 1, 1),
  new THREE.MeshStandardMaterial({ color: 0x44aa88 })
);
scene.add(cube);
scene.add(new THREE.AmbientLight(0xffffff, 0.6));
const dirLight = new THREE.DirectionalLight(0xffffff, 2.5);
dirLight.position.set(3, 5, 2);
scene.add(dirLight);

function animate() {
  requestAnimationFrame(animate);
  cube.rotation.y += 0.01;
  renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>

尝试一下 »

点击 "尝试一下" 按钮查看在线实例

把这段代码保存为 index.html,双击用浏览器打开(或用 VS Code 的 Live Server 插件),就能看到一个深蓝背景、缓慢旋转的青绿色立方体。这个文件包含四个关键点:

importmap 必须写在 module 脚本之前。它告诉浏览器代码里的 three 要去哪个 URL 加载。两个映射缺一不可:three 指向库本体,three/addons/ 指向官方插件目录(控制器、加载器、后期处理都在里面,第 10 章的 OrbitControls 就从这里导入)。

版本号写死在 URL 里。不写版本号或写 latest,某天 Three.js 发新版本删了个 API,你的页面就莫名其妙白屏。锁定版本是 Three.js 项目的第一纪律。

<script type="module"> 不能省。少了它浏览器不认识 import 语法,控制台直接报语法错误。

只有 ES Module 能引入。因为 importmap 在浏览器本地解析模块,这种方式不需要构建工具,是做实验、写 demo、跟教程最快的路径。它的短板是:无法引入 npm 上只有构建版的三方库、没有代码压缩、浏览器兼容性依赖 importmap 支持度(Chrome 89+ / Safari 16.4+ / Firefox 108+,今天的浏览器基本都覆盖)。项目一大,就该换下面的方案了。


正式项目:npm + Vite

要加载 glTF 模型、用 TypeScript、拆分代码文件、最终上线部署,就需要工程化环境。Vite 是当前 Three.js 社区的事实标准:

# 1. 创建一个 vanilla 项目
npm create vite@latest my-threejs-app -- --template vanilla

# 2. 进入目录并安装依赖
cd my-threejs-app
npm install

# 3. 安装 Three.js(锁定版本)
npm install three@0.187.0

# 4. 启动开发服务器
npm run dev

开发服务器默认跑在 http://localhost:5173。把项目里 main.js 的内容替换成上面最小模板 <script type="module"> 里的 JS 代码,只改一行引入方式:

import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

Vite 认识 three 这个包名(它去 node_modules 找),也认识 three/addons/(Three.js 的 package.json 里声明了这个路径映射),所以代码在两种环境里写法完全一致——跟教程学习时用 importmap,做项目时搬进 Vite,代码一个字不用改。

两个日常命令记住即可:npm run dev 边改边看(热更新),npm run build 打包出 dist/ 目录用于部署。


装好三个调试工具

3D 开发的调试方式和普通前端不同:很多问题(转错方向、材质发黑、粒子太稀)不看画面根本发现不了,所以工具栈围绕看得见构建。

浏览器 DevTools:一切的第一站。Three.js 的报错、着色器编译失败、贴图加载 404 全部在 Console 面板。养成习惯:画面不对,先按 F12 看 Console 有没有红字,再动脑猜。

stats.js:帧率监视器。左上角实时显示 FPS,是判断为什么卡的第一证据。它就在 Three.js 官方仓库的插件目录里,不用单独安装:

import Stats from 'three/addons/libs/stats.module.js';

const stats = new Stats();
document.body.appendChild(stats.dom);

function animate() {
  requestAnimationFrame(animate);
  stats.update();        // 放在渲染循环里
  renderer.render(scene, camera);
}

lil-gui:参数调节面板。右上角生成一组滑块和颜色选择器,把材质颜色、光源强度这类参数做成可实时拖动的控件。调材质、调光照的效率比改代码刷新高一个数量级:

import GUI from 'three/addons/libs/lil-gui.module.min.js';

const gui = new GUI();
gui.add(cube.rotation, 'y', 0, Math.PI * 2).name('旋转');
gui.add(cube.material, 'roughness', 0, 1).name('粗糙度');
gui.addColor(cube.material, 'color').name('颜色');

Three.js Inspector 这类场景树检查器近年来基本停止维护,对新版本支持不佳,不推荐再投入时间。想看 glTF 模型的结构,直接把文件拖进官网的在线编辑器 threejs.org/editor 就够了。

下面这个示例把三个工具装在一起,拖一拖面板参数,感受一下所见即所得的调试方式:

集成 stats.js 与 lil-gui 的调试示例

Three.js 实例:调试三件套(stats.js + lil-gui + OrbitControls)

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>调试三件套:stats.js + lil-gui + OrbitControls</title>
<style>
  body { margin: 0; overflow: hidden; background: #1a1a2e; }
</style>
<script type="importmap">
{
  "imports": {
    "three": "https://static.jyshare.com/assets/libs/threejs/three-0.187.0/build/three.module.js",
    "three/addons/": "https://static.jyshare.com/assets/libs/threejs/three-0.187.0/examples/jsm/"
  }
}
</script>
</head>
<body>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import Stats from 'three/addons/libs/stats.module.js';
import GUI from 'three/addons/libs/lil-gui.module.min.js';

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x1a1a2e);

const camera = new THREE.PerspectiveCamera(50, 2, 0.1, 100);
camera.position.set(3, 2, 4);

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);

const cube = new THREE.Mesh(
  new THREE.BoxGeometry(1, 1, 1),
  new THREE.MeshStandardMaterial({ color: 0x44aa88, roughness: 0.4 })
);
scene.add(cube);
scene.add(new THREE.AmbientLight(0xffffff, 0.6));
const dirLight = new THREE.DirectionalLight(0xffffff, 2.5);
dirLight.position.set(3, 5, 2);
scene.add(dirLight);

new OrbitControls(camera, renderer.domElement);

const stats = new Stats();
document.body.appendChild(stats.dom);

const gui = new GUI();
gui.add(cube.material.color, 'r', 0, 1).name('红');
gui.add(cube.material.color, 'g', 0, 1).name('绿');
gui.add(cube.material.color, 'b', 0, 1).name('蓝');
gui.add(cube.material, 'roughness', 0, 1).name('粗糙度');
gui.add(cube.material, 'metalness', 0, 1).name('金属度');
gui.add(dirLight, 'intensity', 0, 5).name('光强');
gui.add(cube.rotation, 'y', 0, Math.PI * 2).name('旋转');

function animate() {
  requestAnimationFrame(animate);
  stats.update();
  renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>

尝试一下 »

点击 "尝试一下" 按钮查看在线实例

其中 OrbitControls 让你用鼠标拖拽旋转视角、滚轮缩放,它是使用频率最高的官方插件,第 10 章正式讲。现在只需要知道:调试面板 + 可拖视角,是后续每一章示例的标准配置。


配置 AI 开发环境

从下一章开始,教程会要求你把 AI 当成结对程序员使用。常见工具按工作方式分三类:

工具工作方式适合
Claude Code终端 Agent:能读整个项目、跑命令、自己测试迭代从零搭场景、批量改代码、自动化截图验证(本教程的 AI 实践示例以它为例)
CursorAI 增强编辑器:对话 + 内联修改 + 上下文索引边写边问、重构、跨文件修改
GitHub Copilot编辑器内补全 + 对话写重复结构时加速,偶尔问问题

工具本身没有高下之分,决定产出质量的是下一节要讲的东西:项目规则文件。工具只是入口,上下文才是燃料。


项目规则文件:给 AI 立规矩

AI 写 Three.js 代码最大的问题不是不会写,而是版本错乱:训练数据里混着 2015 年到今天的各种写法,它经常把已删除的 API 和最新语法混在一坨输出里。解决办法是在项目根目录放一个规则文件,把本项目的版本和规范变成 AI 每次都会读到的上下文。Claude Code 读 CLAUDE.md,Cursor 读 .cursorrules(或 .cursor/rules),内容可以通用。Three.js 项目可直接使用下面这份模板:

# 项目 Three.js 规范

## 版本
- 本项目使用 three@0.187.0(ES Module 版)
- 禁止使用任何旧版全局脚本引入(three.min.js)
- 引入方式:importmap 或 npm + Vite,代码写法一致

## 导入路径
- 库本体:import * as THREE from 'three'
- 官方插件:three/addons/xxx(不要写 three/examples/jsm/xxx)
- 常用插件:controls/OrbitControls.js、loaders/GLTFLoader.js

## 禁用的已删除/过时 API
- THREE.Geometry(r125 已删除):只用 BufferGeometry 系
- renderer.outputEncoding(r152 已删除):色彩空间用 renderer.outputColorSpace = THREE.SRGBColorSpace
- renderer.physicallyCorrectLights(r155 已删除):光照强度单位已改为物理单位,点光/聚光默认 decay=2
- THREE.Clock(r183 已废弃):改用 THREE.Timer,每帧先 timer.update() 再 timer.getDelta()
- WebGL 1 相关特性(r163 起不再支持)

## 渲染规范
- 默认用 WebGLRenderer;仅当需要 TSL/Compute Shader 时用 WebGPURenderer
- 渲染循环用 requestAnimationFrame,动画增量基于 Clock 的 delta,不写死每帧 0.01
- 组件销毁时调用 geometry.dispose() / material.dispose() / texture.dispose()

## 资源
- 模型一律 glTF/GLB 格式,贴图优先 KTX2/basis
- 加载用 LoadingManager 统一管理进度

这份模板覆盖了 AI 最常犯的版本错误(每个都会在后面章节遇到并详细解释)。规则文件要随项目演进:哪次 AI 犯了新错,就把对应条目加进去——它是你和 AI 之间不断补充的合同。

环境到此全部就绪:浏览器能跑 importmap,Vite 能起工程,调试三件套装好,AI 也立好了规矩。下一章正式动手,从零写出第一个完整 3D 场景,并把每一行代码的作用讲透。