当前位置: 首页 > news >正文

Three.js 动画循环学习记录

在上一篇文章中,我们学习了Three.js 坐标系系统与单位理解教程:

Three.js 坐标系系统与单位理解教程

接下来我们要学习的是Three.js 的动画循环

一、动画循环基础原理

1. 什么是动画循环?

        动画循环是连续更新场景状态并重新渲染的过程,通过快速连续的画面变化产生动态效果。在Three.js中,这通常以与显示器刷新率同步的频率执行。

2. 核心代码结构

function animate() {requestAnimationFrame(animate); // 1. 请求下一帧updateScene();                 // 2. 更新场景状态renderer.render(scene, camera); // 3. 渲染场景
}
animate(); // 启动循环

二、Vue3 中的完整实现与解析

1. 组件基础结构(Composition API)

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as THREE from 'three';// DOM 引用
const container = ref(null);// Three.js 核心对象
let scene, camera, renderer, cube;
let animationId = null; // 存储动画ID用于取消
const clock = new THREE.Clock(); // Three.js内置时钟
</script>

2. 初始化函数详解

function initThreeScene() {// 场景初始化scene = new THREE.Scene();scene.background = new THREE.Color(0x111111);// 相机配置(透视相机)camera = new THREE.PerspectiveCamera(75,                         // 视野角度(FOV)window.innerWidth/innerHeight, // 宽高比0.1,                        // 近裁剪面1000                        // 远裁剪面);camera.position.z = 5;        // 相机位置// 渲染器配置renderer = new THREE.WebGLRenderer({ antialias: true,           // 开启抗锯齿alpha: true                // 开启透明度});renderer.setPixelRatio(Math.min(2, window.devicePixelRatio)); // 合理设置像素比renderer.setSize(window.innerWidth, window.innerHeight);container.value.appendChild(renderer.domElement);// 添加测试物体addTestCube();// 启动动画循环startAnimationLoop();
}

3. 动画循环的完整实现

基础版本:

function animate() {// 递归调用形成循环animationId = requestAnimationFrame(animate);// 物体旋转动画cube.rotation.x += 0.01;cube.rotation.y += 0.01;// 渲染场景renderer.render(scene, camera);
}

专业版本(带时间控制):

let previousTime = 0;function animate(currentTime) {animationId = requestAnimationFrame(animate);// 计算时间增量(毫秒转换为秒)const deltaTime = (currentTime - previousTime) / 1000;previousTime = currentTime;// 使用时间增量确保动画速度一致const rotationSpeed = 2; // 弧度/秒cube.rotation.x += rotationSpeed * deltaTime;cube.rotation.y += rotationSpeed * deltaTime;// 弹跳动画(使用正弦函数)const bounceHeight = 0.5;const bounceSpeed = 2;cube.position.y = Math.sin(currentTime * 0.001 * bounceSpeed) * bounceHeight;renderer.render(scene, camera);
}

4. 动画控制与管理

// 启动动画循环
function startAnimationLoop() {if (!animationId) {clock.start(); // 启动Three.js时钟previousTime = performance.now(); // 记录初始时间animate(); // 开始循环}
}// 停止动画循环
function stopAnimationLoop() {if (animationId) {cancelAnimationFrame(animationId);animationId = null;clock.stop(); // 停止时钟}
}// 重置动画状态
function resetAnimation() {cube.rotation.set(0, 0, 0);cube.position.set(0, 0, 0);previousTime = performance.now(); // 重置时间记录
}

三、高级动画技巧

1. 性能优化策略

条件渲染(只在需要时渲染)

let needsUpdate = false;// 当场景变化时调用
function triggerRender() {needsUpdate = true;
}function animate() {animationId = requestAnimationFrame(animate);if (needsUpdate) {renderer.render(scene, camera);needsUpdate = false;}
}

分帧处理(复杂场景优化)

let frameCount = 0;function animate() {animationId = requestAnimationFrame(animate);// 每帧只更新部分元素if (frameCount % 2 === 0) updatePhysics();if (frameCount % 3 === 0) updateBackground();updateMainObjects(); // 主要物体每帧都更新renderer.render(scene, camera);frameCount++;
}

2. 混合动画技术

function animate() {animationId = requestAnimationFrame(animate);const time = clock.getElapsedTime();// 旋转动画cube.rotation.x = time * 1; // 持续旋转// 脉动动画(缩放)const pulseSpeed = 3;const pulseIntensity = 0.2;cube.scale.setScalar(1 + Math.sin(time * pulseSpeed) * pulseIntensity);// 颜色变化cube.material.color.setHSL(Math.sin(time * 0.5) * 0.5 + 0.5, // 色相 (0-1)0.8, // 饱和度0.5  // 亮度);renderer.render(scene, camera);
}

四、Vue3 组件完整实现

<template><!-- 容器用于挂载 Three.js 渲染器 --><div ref="container" class="three-container"></div><!-- 控制面板,包含播放/暂停、重置按钮和 FPS 显示 --><div class="control-panel"><!-- 播放/暂停按钮,点击切换动画状态 --><button @click="toggleAnimation">{{ isPlaying ? '⏸ 暂停' : '▶ 播放' }}</button><!-- 重置动画按钮 --><button @click="resetAnimation">↻ 重置</button><!-- 显示当前 FPS 值 --><span class="fps-counter">FPS: {{ fps.toFixed(1) }}</span></div>
</template><script setup>
// 导入 Vue 的响应式 API
import { ref, onMounted, onBeforeUnmount } from 'vue';
// 导入 Three.js 库
import * as THREE from 'three';// 创建响应式引用:容器 DOM 元素
const container = ref(null);
// 创建响应式引用:动画播放状态
const isPlaying = ref(true);
// 创建响应式引用:FPS 值
const fps = ref(0);// 声明 Three.js 相关对象变量
let scene, camera, renderer, cube;
// 动画帧 ID,用于取消动画循环
let animationId = null;
// Three.js 时钟对象,用于计算时间差
const clock = new THREE.Clock();// FPS 计算相关变量
let lastFpsUpdate = 0;  // 上次更新 FPS 的时间戳
let frameCount = 0;     // 帧计数器// 初始化 Three.js 场景
function initScene() {// 创建场景对象scene = new THREE.Scene();// 设置场景背景颜色scene.background = new THREE.Color(0x222222);// 创建透视相机camera = new THREE.PerspectiveCamera(60, window.innerWidth/window.innerHeight, 0.1, 100);// 设置相机位置camera.position.set(0, 1, 5);// 相机看向原点camera.lookAt(0, 0, 0);// 创建 WebGL 渲染器,开启抗锯齿renderer = new THREE.WebGLRenderer({ antialias: true });// 设置渲染器像素比率renderer.setPixelRatio(window.devicePixelRatio);// 设置渲染器尺寸renderer.setSize(window.innerWidth, window.innerHeight);// 将渲染器的 DOM 元素添加到容器中container.value.appendChild(renderer.domElement);// 创建环境光const ambientLight = new THREE.AmbientLight(0x404040);// 创建方向光const directionalLight = new THREE.DirectionalLight(0xffffff, 1);// 设置方向光位置directionalLight.position.set(1, 1, 1);// 将灯光添加到场景中scene.add(ambientLight, directionalLight);// 添加动画立方体到场景addAnimatedCube();// 添加坐标轴辅助器scene.add(new THREE.AxesHelper(3));// 添加网格辅助器scene.add(new THREE.GridHelper(10, 10));// 开始动画循环startAnimation();
}// 创建并添加动画立方体
function addAnimatedCube() {// 创建立方体几何体const geometry = new THREE.BoxGeometry(1, 1, 1);// 创建标准材质并设置属性const material = new THREE.MeshStandardMaterial({ color: 0x00ff00,      // 颜色roughness: 0.3,       // 粗糙度metalness: 0.7        // 金属度});// 创建网格对象cube = new THREE.Mesh(geometry, material);// 将立方体添加到场景中scene.add(cube);
}// 动画循环函数
function animate(timestamp) {// 请求下一帧动画animationId = requestAnimationFrame(animate);// 更新 FPS 计数器updateFpsCounter(timestamp);// 获取时间差和总时间const delta = clock.getDelta();const elapsed = clock.getElapsedTime();// 更新动画状态updateAnimations(elapsed, delta);// 渲染场景renderer.render(scene, camera);
}// 更新所有动画效果
function updateAnimations(time, delta) {// 立方体绕 X 轴旋转cube.rotation.x = time * 0.5;// 立方体绕 Y 轴旋转cube.rotation.y = time * 0.3;// 立方体上下弹跳效果cube.position.y = Math.sin(time * 2) * 0.5;// 立方体颜色随时间变化cube.material.color.setHSL((Math.sin(time * 0.3) + 1) / 2,  // 色相0.8,                              // 饱和度0.6                               // 亮度);
}// 更新 FPS 计数器
function updateFpsCounter(timestamp) {// 帧数递增frameCount++;// 每秒更新一次 FPS 值if (timestamp >= lastFpsUpdate + 1000) {fps.value = (frameCount * 1000) / (timestamp - lastFpsUpdate);// 重置帧计数器和更新时间frameCount = 0;lastFpsUpdate = timestamp;}
}// 控制动画播放的方法
function startAnimation() {// 如果动画未运行则开始动画if (!animationId) {clock.start();animationId = requestAnimationFrame(animate);isPlaying.value = true;}
}// 停止动画
function stopAnimation() {// 如果动画正在运行则停止if (animationId) {cancelAnimationFrame(animationId);animationId = null;clock.stop();isPlaying.value = false;}
}// 切换动画播放状态
function toggleAnimation() {if (isPlaying.value) stopAnimation();else startAnimation();
}// 重置动画状态
function resetAnimation() {// 重置立方体旋转cube.rotation.set(0, 0, 0);// 重置立方体位置cube.position.set(0, 0, 0);// 重置立方体缩放cube.scale.set(1, 1, 1);// 重置立方体颜色cube.material.color.set(0x00ff00);// 重启时钟clock.start();
}// 窗口大小调整处理函数
function onResize() {// 更新相机宽高比camera.aspect = window.innerWidth / window.innerHeight;// 更新相机投影矩阵camera.updateProjectionMatrix();// 更新渲染器尺寸renderer.setSize(window.innerWidth, window.innerHeight);
}// 组件挂载时执行
onMounted(() => {// 初始化场景initScene();// 添加窗口大小调整事件监听器window.addEventListener('resize', onResize);
});// 组件卸载前执行清理工作
onBeforeUnmount(() => {// 停止动画stopAnimation();// 移除窗口大小调整事件监听器window.removeEventListener('resize', onResize);// 释放渲染器资源if (renderer) {renderer.dispose();renderer.forceContextLoss();}
});
</script><style>
/* Three.js 容器样式 */
.three-container {position: fixed;top: 0;left: 0;width: 100%;height: 100%;outline: none;
}/* 控制面板样式 */
.control-panel {position: fixed;bottom: 20px;left: 50%;transform: translateX(-50%);display: flex;gap: 10px;align-items: center;background: rgba(0, 0, 0, 0.7);padding: 10px 15px;border-radius: 20px;color: white;
}/* 控制面板按钮样式 */
.control-panel button {background: rgba(255, 255, 255, 0.1);border: 1px solid rgba(255, 255, 255, 0.3);color: white;padding: 5px 12px;border-radius: 15px;cursor: pointer;transition: all 0.2s;
}/* 按钮悬停效果 */
.control-panel button:hover {background: rgba(255, 255, 255, 0.2);
}/* FPS 计数器样式 */
.fps-counter {font-family: monospace;min-width: 80px;display: inline-block;text-align: center;
}
</style>

实现效果

three.js动画

五、关键知识点总结

  1. 动画循环三要素

    • requestAnimationFrame 递归调用

    • 场景状态更新

    • 渲染器执行渲染

  2. 时间控制的重要性

    • 使用 performance.now() 或 THREE.Clock

    • 通过 delta time 确保动画速度一致

  3. 性能优化方向

    • 条件渲染(只在需要时渲染)

    • 分帧处理(复杂场景优化)

    • 合理使用 dispose() 释放资源

  4. Vue3 集成要点

    • 在 onMounted 中初始化

    • 在 onBeforeUnmount 中清理

    • 使用 ref 管理DOM元素引用

  5. 调试技巧

    • 添加FPS计数器监控性能

    • 使用坐标辅助器查看空间关系

    • 实现动画控制按钮方便调试

       这个实现展示了专业级的Three.js动画循环管理,包含了性能优化、时间控制、状态管理等关键要素,可以直接用于生产环境项目。

http://www.dtcms.com/a/338252.html

相关文章:

  • 6 webUI中图生图重绘方式--涂鸦、涂鸦重绘、局部重绘、上传蒙版重绘
  • 生成式引擎优化(GEO)AI搜索优化专家竞争力报告
  • 检测手绘图中不规则曲线交点的方法和一般规则线条交点的方法
  • rom定制系列------小米cc9机型 原生安卓15系统 双版线刷root 定制修改功能项
  • 力扣(分发糖果)
  • 【完整源码+数据集+部署教程】海洋垃圾与生物识别系统源码和数据集:改进yolo11-RVB
  • 深度优先遍历dfs(模板)
  • VS Code Copilot 完整使用教程(含图解)
  • 【笔记ing】考试脑科学 脑科学中的高效记忆法
  • 图论:Floyd算法
  • 从数学原理推导的角度介绍大语言MOE架构的本质
  • Linux系统WireShark抓取本地网卡报文
  • uv 现代化的虚拟环境管理工具
  • 量化线性层,将原始的fp16/bf16权重加载到Linear8bitLt模块中,调用int8_module.to(“cuda”)量化 (44)
  • 视频讲解:CatBoost、梯度提升 (XGBoost、LightGBM)对心理健康数据、交通流量及股票价格预测研究
  • Dubbo 的SPI
  • 深入解析RabbitMQ与AMQP-CPP:从原理到实战应用
  • IDEA 配置终端提示符样式,通过脚本方式
  • IntelliJ IDEA 开发配置教程
  • WPF---数据模版
  • 监督学习(Supervised Learning)和 无监督学习(Unsupervised Learning)详解
  • PCIe ASPM详解
  • 14.Linux线程(2)线程同步、线程安全、线程与fork
  • 【秋招笔试】2025.08.17大疆秋招机考第一套
  • plantsimulation知识点25.8.18-从一个RGV到另一台RGV,工件长度和宽度方向互换
  • pytest测试框架之基本用法
  • GPT-5之后:当大模型更新不再是唯一焦点
  • 本地搭建dify+deepseek智能体
  • 【unitrix数间混合计算】3.1 零标记trait(zero.rs)
  • 【最后203篇系列】033 Mongo副本集修复过程