引言
glTF 被称为「3D 界的 JPEG」,是 Three.js 官方推荐、也是行业事实标准的模型交换格式。在真实的 3D 项目里,角色、设备、建筑、地形道具几乎都以 .gltf 或 .glb 的形式交付。但很多新手第一次接入模型时都会卡在几个地方:控制台报路径 404、模型加载出来却黑屏、导入后模型要么小到看不见要么撑爆视口、好不容易显示出来了动画却一动不动。
本文以 GLTFLoader 为主线,带你走完一次完整的模型加载与控制流程:如何正确处理二进制打包、如何用 Draco 解压压缩过的几何体、如何把任意尺寸的模型自动居中并缩放进视口,以及最后如何用 AnimationMixer 把关键帧动画播起来。
原理
glTF 本质上是一份描述场景的 JSON,外加顶点、索引、贴图等二进制数据。GLTFLoader 会解析这份描述,还原出 Three.js 的 Scene(其实是一个 Group),里面装着 Mesh、Material 以及 AnimationClip。.gltf 通常是 JSON 加外部的 .bin 和资源文件,而 .glb 是把它们打包成单个二进制文件,部署更方便。
Draco 是一种开源的几何压缩算法,能把顶点、法线、索引等数据压得很小(常见能缩到原来的 1/5 甚至更小),代价是浏览器端需要额外的解码步骤。GLTFLoader 本身不内置解码器,必须挂一个 DRACOLoader,并告诉它去哪里加载 wasm 解码器目录。
动画部分由 AnimationMixer 负责。每个模型可能带有若干 AnimationClip,mixer 把某个 clip 和一个 root 对象绑定成 AnimationAction,之后每一帧调用 mixer.update(delta) 推进时间轴,模型就会动起来。
代码实现
下面是一段可直接运行的最小示例(ESM + CDN,用 importmap 引入 three):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8" /> <title>GLTFLoader Demo</title> <style>html,body{margin:0;height:100%;overflow:hidden}#app{width:100%;height:100%}</style> </head> <body> <div id="app"></div> <script type="importmap"> { "imports": { "three": "https://unpkg.com/three@0.160.0/build/three.module.js", "three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/" } } </script> <script type="module"> import * as THREE from 'three'; import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
const app = document.getElementById('app'); const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(app.clientWidth, app.clientHeight); renderer.setPixelRatio(Math.min(devicePixelRatio, 2)); app.appendChild(renderer.domElement);
const scene = new THREE.Scene(); scene.background = new THREE.Color(0x1a1a1a);
const camera = new THREE.PerspectiveCamera(45, app.clientWidth / app.clientHeight, 0.1, 1000); camera.position.set(3, 2, 5);
const controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true;
scene.add(new THREE.HemisphereLight(0xffffff, 0x444444, 1.2)); const dir = new THREE.DirectionalLight(0xffffff, 2); dir.position.set(5, 10, 7); scene.add(dir);
let mixer = null; const clock = new THREE.Clock();
const draco = new DRACOLoader(); draco.setDecoderPath('https://unpkg.com/three@0.160.0/examples/jsm/libs/draco/');
const loader = new GLTFLoader(); loader.setDRACOLoader(draco);
loader.load( 'https://your-cdn.com/models/robot.glb', (gltf) => { const model = gltf.scene;
const box = new THREE.Box3().setFromObject(model); const size = box.getSize(new THREE.Vector3()); const center = box.getCenter(new THREE.Vector3()); const maxDim = Math.max(size.x, size.y, size.z); const scale = 2 / maxDim; model.scale.setScalar(scale); model.position.sub(center.multiplyScalar(scale));
scene.add(model);
if (gltf.animations.length > 0) { mixer = new THREE.AnimationMixer(model); mixer.clipAction(gltf.animations[0]).play(); } }, (xhr) => { if (xhr.total) console.log('加载进度', (xhr.loaded / xhr.total * 100).toFixed(1) + '%'); }, (err) => console.error('模型加载失败', err) );
renderer.setAnimationLoop(() => { const delta = clock.getDelta(); if (mixer) mixer.update(delta); controls.update(); renderer.render(scene, camera); });
addEventListener('resize', () => { camera.aspect = app.clientWidth / app.clientHeight; camera.updateProjectionMatrix(); renderer.setSize(app.clientWidth, app.clientHeight); }); </script> </body> </html>
|
把代码里的 https://your-cdn.com/models/robot.glb 换成你自己的模型地址即可。如果是未压缩的模型,删掉 DRACOLoader 相关三行也无影响。
常见坑
模型不显示或尺寸离谱:建模软件导出的单位和原点千差万别。不要手动猜 scale,而是像示例中那样用 Box3 量出包围盒,再按最大边归一化到固定尺寸,并沿包围盒中心做平移,保证任何模型都稳稳落在原点附近。
Draco 黑屏:挂了 DRACOLoader 却忘了 setDecoderPath,或者路径指向了不存在的目录,浏览器拿不到 wasm 解码器,模型会静默失败。路径可以指向 CDN 的 draco/ 目录,也可以把 examples/jsm/libs/draco/ 拷到自己的服务器下。
PBR 材质发黑:glTF 的 MeshStandardMaterial 依赖光照与环境反射。只加一个方向光往往不够,补一盏 HemisphereLight,必要时用 RoomEnvironment 生成环境贴图赋给 scene.environment,金属和粗糙质感才会正确。
动画不动:AnimationMixer 必须每帧 update(delta) 才会推进,且要确认 gltf.animations 数组非空、绑定的 root 是 gltf.scene 本身。若模型有多个 clip,用名字精确定位:THREE.AnimationClip.findByName(gltf.animations, 'Walk')。
跨域 404 / CORS:模型和资源必须和服务端同源,或服务器返回正确的 Access-Control-Allow-Origin 头;直接以 file:// 打开本地 HTML 会被浏览器拦截,一定要起一个本地静态服务器再访问。
小结
GLTFLoader 是 Three.js 接入真实模型的入口,配合 DRACOLoader 处理压缩几何体、Box3 做自适应居中缩放、HemisphereLight 解决打光、AnimationMixer 驱动动画,就覆盖了从「加载出来」到「好看且会动」的完整链路。记住这五个坑,下次接入角色或设备模型时就能少走很多弯路。