Three.js加载Gltf模型并播放动画
发布时间:2026/10/14 9:05:47 锦皓数字建站

老规矩初始化相机场景渲染器等这里不过多赘述详情看上一篇文章。从0搭建一个3D立体场景光影与交互全解析-CSDN博客基本使用只要在文件中引入这个即可const loader new GLTFLoader(); loader.load(https://threejs.org/examples/models/gltf/Soldier.glb, (gltf) { window.gltf gltf scene.add(gltf.scene); });GLTF模型中可以存储3D建模软件中做好的动画。创建好的动画会存储在模型对象的animatinos属性中Three.js只需要调用播放动画即可。动画调用//设置动画 const animations gltf.animations; //初始化动画混合器 mixer new THREE.AnimationMixer(model); //添加动画 播放第二个动画 mixer.clipAction(animations[1]).play(); //或者找到某一个动画效果 //const walkAnimation animations.find(animation animation.name Walk);// 最后在动画循环中一调用即可 function animate() { requestAnimationFrame(animate); //更新动画混合器 mixer.update(0.016); controls.update(); renderer.render(scene, camera); } animate();最后你就可以看到一个动态的模型啦源码// 使用现有3d模型 import ./style.css; import * as THREE from three; import { OrbitControls } from three/examples/jsm/controls/OrbitControls.js; import { GLTFLoader } from three/examples/jsm/loaders/GLTFLoader.js; // 初始化相机、场景、渲染器等 const canvas document.getElementById(webgl); const camera new THREE.PerspectiveCamera(30, window.innerWidth / window.innerHeight, 1, 3000); camera.position.set(100, 100, 100); camera.lookAt(0, 0, 0); // 创建场景 const scene new THREE.Scene(); // 创建渲染器 const renderer new THREE.WebGLRenderer({ antialias: true, canvas: canvas }); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(window.innerWidth, window.innerHeight); // 创建控制器 const controls new OrbitControls(camera, renderer.domElement); controls.target.set(0, 0, 0); controls.update(); //开启阴影支持 renderer.shadowMap.enabled true //设置阴影类型PCFSoftShadowMap 是软阴影边缘带有模糊效果PCFShadowMap 是硬阴影 renderer.shadowMap.type THREE.PCFSoftShadowMap; //设置场景背景颜色改为浅灰色方便更好形成明暗对比 renderer.setClearColor(0x262626); //布局灯光 // 环境光 const ambientLight new THREE.AmbientLight(0xffffff, 0.5); scene.add(ambientLight); //平行光 const sunLight new THREE.DirectionalLight(0xffffff, 1); sunLight.position.set(1, 1, 1); scene.add(sunLight); //开启主光源的阴影 sunLight.castShadow true; // // 优化阴影的精细度 // // 默认的阴影贴图可能比较糊这里将其分辨率调大一倍 (默认是 512x512) // sunLight.shadow.mapSize.width 1024; // sunLight.shadow.mapSize.height 1024; //声明动画混合器变量 let mixer: THREE.AnimationMixer; //引入模型 const loader new GLTFLoader(); loader.load(https://threejs.org/examples/models/gltf/Soldier.glb, (gltf) { const model gltf.scene; //设置模型位置为中心场景方便观察 model.position.y 0; model.scale.setScalar(20); //设置动画 const animations gltf.animations; //初始化动画混合器 mixer new THREE.AnimationMixer(model); //添加动画 播放第二个动画 mixer.clipAction(animations[1]).play(); //const walkAnimation animations.find(animation animation.name Walk); scene.add(model); }); // 动画循环 function animate() { requestAnimationFrame(animate); //更新动画混合器 mixer.update(0.016); controls.update(); renderer.render(scene, camera); } animate();
锦
锦皓数字建站
深耕本土企业品牌数字化升级,专注原创端正雅致商务官网,从视觉设计到稳定运维全程保驾护航。