利用KeyframeTrack添加帧数据,AnimationClip创建动画片段,将片段对象传入AnimationMixer播放器中,使用mixer返回AnimationAction控制播放。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<canvas width="500" height="500"></canvas>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.144.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.144.0/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
const canv = document.querySelector("canvas");
// 基础三件套
const renderer = new THREE.WebGLRenderer({
canvas: canv,
premultipliedAlpha: false,
});
const camera = new THREE.OrthographicCamera(-500, 500, 500, -500, 500, -500);
const scene = new THREE.Scene();
// 简单设置调整
camera.position.set(0, 0, 100);
// 添加一个立方体
const cubeGeo = new THREE.BoxGeometry(100, 100, 100);
const cubeMtl = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const cube = new THREE.Mesh(cubeGeo, cubeMtl);
scene.add(cube);
// 创建关键帧轨道0秒时取值0,2秒时取值400
const trackX = new THREE.KeyframeTrack(
".position[x]",
[0, 2],
[0, 400],
THREE.InterpolateLinear
);
// 0秒时取值0,2秒时取值400
const trackY = new THREE.KeyframeTrack(
".position[y]",
[2, 4],
[0, 400],
THREE.InterpolateLinear
);
// 创建片段
const clip = new THREE.AnimationClip(null, 6, [trackX, trackY]);
// 创建动画播放器,同时绑定动画对象
const mixer = new THREE.AnimationMixer(cube);
// 添加片段,获取片段控制器
const action = mixer.clipAction(clip);
// 播放片段,要结合mixer.update
action.play();
// 渲染
const clock = new THREE.Clock();
function render() {
mixer.update(clock.getDelta());
renderer.render(scene, camera);
}
renderer.setAnimationLoop(render);
</script>
</body>
</html>