如果你是初学者,那么学习三维动画可能是一项比较困难的任务。但是,使用 three.js 这个强大的 JavaScript 库,可以让你轻松地制作出精美的三维动画。
首先,我们需要导入 three.js 库,并创建场景、相机和渲染器。场景是三维空间中所有物体的容器,而相机则决定了我们所看到的视角。渲染器则负责将场景呈现在屏幕上。
接下来,我们可以使用 OrbitControls 插件来控制相机的位置和视角,并使用 GLTFLoader 插件来加载三维模型文件。这里我们使用的是 donuts.glb 文件,它包含了一个甜甜圈的三维模型。
为了让我们的场景更加逼真,我们还可以使用 RGBELoader 插件来加载环境贴图,并将它设置为场景的背景。这样,我们就可以在我们的三维模型中感受到周围环境的光照效果了。
最后,我们还可以在动画函数中添加代码来自动旋转模型,并播放它的动画。这样,我们就可以轻松地制作出精彩的三维动画了。
总的来说,使用 three.js 制作三维动画非常方便,它提供了丰富的插件和 API,让我们能够快速上手。如果你也想学习 three.js,不妨加入猿创营(v:dashuailaoyuan),一起交流学习。
import * as THREE from 'three';
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader';
// 三D三大件
// 场景
const scene = new THREE.Scene();
// 相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/innerHeight, 0.1, 10)
// 渲染器
const renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 设置相机位置
camera.position.set(0.3,0.3,0.5);
// 添加 控制器,可以拖拽,缩放
const controls = new OrbitControls(camera, renderer.domElement);
// 添加灯光,DirectionLight方向光
const directionLight = new THREE.DirectionalLight(0xffffff, 0.4);
// scene.add(directionLight);
let donuts;
let mixer;
// 加载 glb 模型
new GLTFLoader().load('../resources/models/donuts.glb', (gltf) => {
// 模型添加到场景
scene.add(gltf.scene);
donuts = gltf.scene;
//
mixer = new THREE.AnimationMixer(gltf.scene);
const clips = gltf.animations;
clips.forEach((clip) => {
const action = mixer.clipAction(clip);
action.loop = THREE.LoopOnce;
action.clampWhenFinished = true;
action.play();
})
})
// 加载环境贴图 360全景图
new RGBELoader()
.load('../resources/sky.hdr', (texture) => {
// 设置为场景背景
scene.background = texture;
texture.mapping = THREE.EquirectangularReflectionMapping;
// 设置环境光
scene.environment = texture;
renderer.outputEncoding = THREE.sRGBEncoding;
renderer.render(scene, camera);
});
function animate() {
requestAnimationFrame(animate);
// 渲染场景
renderer.render(scene, camera);
// 更新控制器
controls.update();
// 自动旋转
if (donuts) {
donuts.rotation.y += 0.001;
}
// 播放动画
if (mixer) {
mixer.update(0.003);
}
}
animate();