Communitygithub.com

BEKO2210/Firstbrain

Three.js 动画 - 关键帧动画、骨骼动画、形态目标、动画混合。适用于动画对象、播放GLTF动画、创建程序化运动或混合动画。

Firstbrain 是什么?

该技能为Three.js场景中构建基于时间的运动行为提供全面的技术指南,超越了静态渲染的限制。它系统地涵盖了核心动画架构(AnimationClip, AnimationMixer, AnimationAction),详细的关键帧轨道类型与插值模式,GLTF模型动画加载,骨骼动画与程序化骨骼控制,形态目标变形,以及高级动画混合(包括加性混合)。此外,还提供了平滑阻尼、弹簧物理和振荡等程序化动画模式,并附有性能优化建议。技能内容适用于所有Three.js版本,特别强调了r183版本中推荐的`THREE.Timer`计时器和新增的`THREE.BezierInterpolant`贝塞尔插值方案。文档结构清晰,包含大量可直接复用的代码示例和实用模式,是Three.js开发者在代理工作流中实现复杂动画的理想参考。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/BEKO2210/Firstbrain/tree/HEAD/03%20-%20Resources/Skills/threejs-animation

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Three.js 动画

使用时机

  • 您需要在Three.js中动画对象、骨骼、形态目标或导入的GLTF动画。
  • 任务涉及混合器、剪辑、关键帧、程序化运动或动画混合。
  • 您正在Three.js场景中构建运动行为,而不仅仅是静态渲染。

快速开始

import * as THREE from "three";

// 使用Timer进行简单程序化动画(r183起推荐)
const timer = new THREE.Timer();

renderer.setAnimationLoop(() => {
  timer.update();
  const delta = timer.getDelta();
  const elapsed = timer.getElapsed();

  mesh.rotation.y += delta;
  mesh.position.y = Math.sin(elapsed) * 0.5;

  renderer.render(scene, camera);
});

注意: 自 r183 起,推荐使用 THREE.Timer 而非 THREE.Clock。Timer 在页面隐藏时会暂停,且 API 更简洁。THREE.Clock 仍然可用,但被视为遗留接口。

动画系统概述

Three.js 动画系统包含三个主要组件:

  1. AnimationClip - 关键帧数据的容器
  2. AnimationMixer - 在根对象上播放动画
  3. AnimationAction - 控制剪辑的播放

AnimationClip

存储关键帧动画数据。

// 创建动画剪辑
const times = [0, 1, 2]; // 关键帧时间(秒)
const values = [0, 1, 0]; // 每个关键帧的值

const track = new THREE.NumberKeyframeTrack(
  ".position[y]", // 属性路径
  times,
  values,
);

const clip = new THREE.AnimationClip("bounce", 2, [track]);

关键帧轨道类型

// 数值轨道(单一值)
new THREE.NumberKeyframeTrack(".opacity", times, [1, 0]);
new THREE.NumberKeyframeTrack(".material.opacity", times, [1, 0]);

// 向量轨道(位置、缩放)
new THREE.VectorKeyframeTrack(".position", times, [
  0,
  0,
  0, // t=0
  1,
  2,
  0, // t=1
  0,
  0,
  0, // t=2
]);

// 四元数轨道(旋转)
const q1 = new THREE.Quaternion().setFromEuler(new THREE.Euler(0, 0, 0));
const q2 = new THREE.Quaternion().setFromEuler(new THREE.Euler(0, Math.PI, 0));
new THREE.QuaternionKeyframeTrack(
  ".quaternion",
  [0, 1],
  [q1.x, q1.y, q1.z, q1.w, q2.x, q2.y, q2.z, q2.w],
);

// 颜色轨道
new THREE.ColorKeyframeTrack(".material.color", times, [
  1,
  0,
  0, // 红色
  0,
  1,
  0, // 绿色
  0,
  0,
  1, // 蓝色
]);

// 布尔轨道
new THREE.BooleanKeyframeTrack(".visible", [0, 0.5, 1], [true, false, true]);

// 字符串轨道(用于形态目标)
new THREE.StringKeyframeTrack(
  ".morphTargetInfluences[smile]",
  [0, 1],
  ["0", "1"],
);

插值模式

const track = new THREE.VectorKeyframeTrack(".position", times, values);

// 插值
 track.setInterpolation(THREE.InterpolateLinear); // 默认
 track.setInterpolation(THREE.InterpolateSmooth); // 三次样条
 track.setInterpolation(THREE.InterpolateDiscrete); // 阶跃函数

BezierInterpolant(r183)

Three.js r183 添加了 THREE.BezierInterpolant,用于关键帧轨道中的贝塞尔曲线插值,通过切线控制实现更平滑的动画曲线。

AnimationMixer

在对象及其子对象上播放动画。

const mixer = new THREE.AnimationMixer(model);

// 从剪辑创建动作
const action = mixer.clipAction(clip);
action.play();

// 在动画循环中更新
function animate() {
  const delta = clock.getDelta();
  mixer.update(delta); // 必需!

  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}

混合器事件

mixer.addEventListener("finished", (e) => {
  console.log("动画完成:", e.action.getClip().name);
});

mixer.addEventListener("loop", (e) => {
  console.log("动画循环:", e.action.getClip().name);
});

AnimationAction

控制动画剪辑的播放。

const action = mixer.clipAction(clip);

// 播放控制
action.play();
action.stop();
action.reset();
action.halt(fadeOutDuration);

// 播放状态
action.isRunning();
action.isScheduled();

// 时间控制
action.time = 0.5; // 当前时间
action.timeScale = 1; // 播放速度(负值表示反向)
action.paused = false;

// 权重(用于混合)
action.weight = 1; // 0-1,对最终姿态的贡献
action.setEffectiveWeight(1);

// 循环模式
action.loop = THREE.LoopRepeat; // 默认:无限循环
action.loop = THREE.LoopOnce; // 播放一次后停止
action.loop = THREE.LoopPingPong; // 来回交替播放
action.repetitions = 3; // 循环次数(默认 Infinity)

// 夹持
action.clampWhenFinished = true; // 完成时保持最后一帧

// 混合
action.blendMode = THREE.NormalAnimationBlendMode;
action.blendMode = THREE.AdditiveAnimationBlendMode;

淡入/淡出

// 淡入
action.reset().fadeIn(0.5).play();

// 淡出
action.fadeOut(0.5);

// 动画间交叉淡入淡出
const action1 = mixer.clipAction(clip1);
const action2 = mixer.clipAction(clip2);

action1.play();

// 稍后,交叉淡入到 action2
action1.crossFadeTo(action2, 0.5, true);
action2.play();

加载 GLTF 动画

骨骼动画最常见的来源。

import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";

const loader = new GLTFLoader();
loader.load("model.glb", (gltf) => {
  const model = gltf.scene;
  scene.add(model);

  // 创建混合器
  const mixer = new THREE.AnimationMixer(model);

  // 获取所有剪辑
  const clips = gltf.animations;
  console.log(
    "可用动画:",
    clips.map((c) => c.name),
  );

  // 播放第一个动画
  if (clips.length > 0) {
    const action = mixer.clipAction(clips[0]);
    action.play();
  }

  // 按名称播放特定动画
  const walkClip = THREE.AnimationClip.findByName(clips, "Walk");
  if (walkClip) {
    mixer.clipAction(walkClip).play();
  }

  // 存储混合器以供更新循环使用
  window.mixer = mixer;
});

// 动画循环
function animate() {
  const delta = clock.getDelta();
  if (window.mixer) window.mixer.update(delta);

  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}

骨骼动画

骨骼与关节

// 从蒙皮网格访问骨骼
const skinnedMesh = model.getObjectByProperty("type", "SkinnedMesh");
const skeleton = skinnedMesh.skeleton;

// 访问骨骼
skeleton.bones.forEach((bone) => {
  console.log(bone.name, bone.position, bone.rotation);
});

// 按名称查找特定骨骼
const headBone = skeleton.bones.find((b) => b.name === "Head");
if (headBone) headBone.rotation.y = Math.PI / 4; // 转动头部

// 骨骼辅助器
const helper = new THREE.SkeletonHelper(model);
scene.add(helper);

程序化骨骼动画

function animate() {
  const time = clock.getElapsedTime();

  // 动画骨骼
  const headBone = skeleton.bones.find((b) => b.name === "Head");
  if (headBone) {
    headBone.rotation.y = Math.sin(time) * 0.3;
  }

  // 如果同时播放剪辑,更新混合器
  mixer.update(clock.getDelta());
}

骨骼附着

// 将对象附着到骨骼
const weapon = new THREE.Mesh(weaponGeometry, weaponMaterial);
const handBone = skeleton.bones.find((b) => b.name === "RightHand");
if (handBone) handBone.add(weapon);

// 偏移附着
weapon.position.set(0, 0, 0.5);
weapon.rotation.set(0, Math.PI / 2, 0);

形态目标

在不同网格形状之间混合。

// 形态目标存储在几何体中
const geometry = mesh.geometry;
console.log("形态属性:", Object.keys(geometry.morphAttributes));

// 访问形态目标影响
mesh.morphTargetInfluences; // 权重数组
mesh.morphTargetDictionary; // 名称 -> 索引映射

// 按索引设置形态目标
mesh.morphTargetInfluences[0] = 0.5;

// 按名称设置
const smileIndex = mesh.morphTargetDictionary["smile"];
mesh.morphTargetInfluences[smileIndex] = 1;

动画形态目标

// 程序化
function animate() {
  const t = clock.getElapsedTime();
  mesh.morphTargetInfluences[0] = (Math.sin(t) + 1) / 2;
}

// 使用关键帧动画
const track = new THREE.NumberKeyframeTrack(
  ".morphTargetInfluences[smile]",
  [0, 0.5, 1],
  [0, 1, 0],
);
const clip = new THREE.AnimationClip("smile", 1, [track]);
mixer.clipAction(clip).play();

动画混合

将多个动画混合在一起。

// 设置动作
const idleAction = mixer.clipAction(idleClip);
const walkAction = mixer.clipAction(walkClip);
const runAction = mixer.clipAction(runClip);

// 以不同权重播放所有动作
idleAction.play();
walkAction.play();
runAction.play();

// 设置初始权重
idleAction.setEffectiveWeight(1);
walkAction.setEffectiveWeight(0);
runAction.setEffectiveWeight(0);

// 根据速度混合
function updateAnimations(speed) {
  if (speed < 0.1) {
    idleAction.setEffectiveWeight(1);
    walkAction.setEffectiveWeight(0);
    runAction.setEffectiveWeight(0);
  } else if (speed < 5) {
    const t = speed / 5;
    idleAction.setEffectiveWeight(1 - t);
    walkAction.setEffectiveWeight(t);
    runAction.setEffectiveWeight(0);
  } else {
    const t = Math.min((speed - 5) / 5, 1);
    idleAction.setEffectiveWeight(0);
    walkAction.setEffectiveWeight(1 - t);
    runAction.setEffectiveWeight(t);
  }
}

加性混合

// 基础姿态
const baseAction = mixer.clipAction(baseClip);
baseAction.play();

// 加性层(例如呼吸)
const additiveAction = mixer.clipAction(additiveClip);
additiveAction.blendMode = THREE.AdditiveAnimationBlendMode;
additiveAction.play();

// 将剪辑转换为加性
THREE.AnimationUtils.makeClipAdditive(additiveClip);

动画实用工具

import * as THREE from "three";

// 按名称查找剪辑
const clip = THREE.AnimationClip.findByName(clips, "Walk");

// 创建子剪辑
const subclip = THREE.AnimationUtils.subclip(clip, "subclip", 0, 30, 30);

// 转换为加性
THREE.AnimationUtils.makeClipAdditive(clip);
THREE.AnimationUtils.makeClipAdditive(clip, 0, referenceClip);

// 克隆剪辑
const clone = clip.clone();

// 获取剪辑时长
clip.duration;

// 优化剪辑(移除冗余关键帧)
clip.optimize();

// 将剪辑重置到第一帧
clip.resetDuration();

程序化动画模式

平滑阻尼

// 平滑跟随/线性插值
const target = new THREE.Vector3();
const current = new THREE.Vector3();
const velocity = new THREE.Vector3();

function smoothDamp(current, target, velocity, smoothTime, deltaTime) {
  const omega = 2 / smoothTime;
  const x = omega * deltaTime;
  const exp = 1 / (1 + x + 0.48 * x * x + 0.235 * x * x * x);
  const change = current.clone().sub(target);
  const temp = velocity
    .clone()
    .add(change.clone().multiplyScalar(omega))
    .multiplyScalar(deltaTime);
  velocity.sub(temp.clone().multiplyScalar(omega)).multiplyScalar(exp);
  return target.clone().add(change.add(temp).multiplyScalar(exp));
}

function animate() {
  current.copy(smoothDamp(current, target, velocity, 0.3, delta));
  mesh.position.copy(current);
}

弹簧物理

class Spring {
  constructor(stiffness = 100, damping = 10) {
    this.stiffness = stiffness;
    this.damping = damping;
    this.position = 0;
    this.velocity = 0;
    this.target = 0;
  }

  update(dt) {
    const force = -this.stiffness * (this.position - this.target);
    const dampingForce = -this.damping * this.velocity;
    this.velocity += (force + dampingForce) * dt;
    this.position += this.velocity * dt;
    return this.position;
  }
}

const spring = new Spring(100, 10);
spring.target = 1;

function animate() {
  mesh.position.y = spring.update(delta);
}

振荡

function animate() {
  const t = clock.getElapsedTime();

  // 正弦波
  mesh.position.y = Math.sin(t * 2) * 0.5;

  // 弹跳
  mesh.position.y = Math.abs(Math.sin(t * 3)) * 2;

  // 圆周运动
  mesh.position.x = Math.cos(t) * 2;
  mesh.position.z = Math.sin(t) * 2;

  // 8字运动
  mesh.position.x = Math.sin(t) * 2;
  mesh.position.z = Math.sin(t * 2) * 1;
}

性能技巧

  1. 共享剪辑:同一 AnimationClip 可用于多个混合器
  2. 优化剪辑:调用 clip.optimize() 以移除冗余关键帧
  3. 离屏时禁用:对不可见对象停止混合器更新
  4. 为动画使用 LOD:对远处角色使用更简单的骨骼
  5. 限制活动混合器数量:每个 mixer.update() 都有性能成本
// 不可见时暂停动画
mesh.onBeforeRender = () => {
  action.paused = false;
};

mesh.onAfterRender = () => {
  // 检查下一帧是否可见
  if (!isInFrustum(mesh)) {
    action.paused = true;
  }
};

// 缓存剪辑
const clipCache = new Map();
function getClip(name) {
  if (!clipCache.has(name)) {
    clipCache.set(name, loadClip(name));
  }
  return clipCache.get(name);
}

参见

  • threejs-loaders - 加载动画 GLTF 模型
  • threejs-fundamentals - 时钟和动画循环
  • threejs-shaders - 着色器中的顶点动画

连接

  • 领域: [[设计与创意]]
  • 类别: [[3D 与动画]]
  • 导航: [[技能概览]],[[首页]]

Individual skills in this repo

This repo contains 18 individual skills — each has its own dedicated page.

BEKO2210/Firstbrain

Skill for discovering and researching autonomous AI agents, tools, and ecosystems using the AgentFolio directory.

BEKO2210/Firstbrain

Advanced JavaScript animation library skill for creating complex, high-performance web animations.

BEKO2210/Firstbrain

One sentence - what this skill does and when to invoke it

BEKO2210/Firstbrain

Audit and fix animation performance issues including layout thrashing, compositor properties, scroll-linked motion, and blur effects. Use when animations stutter, transitions jank, or reviewing CSS/JS animation performance.

BEKO2210/Firstbrain

Internationalization and localization patterns. Detecting hardcoded strings, managing translations, locale files, RTL support.

BEKO2210/Firstbrain

Expert in building portfolios that actually land jobs and clients -

BEKO2210/Firstbrain

Generates high-converting Next.js/React landing pages with Tailwind CSS. Uses PAS, AIDA, and BAB frameworks for optimized copy/components (Heroes, Features, Pricing). Focuses on Core Web Vitals/SEO.

BEKO2210/Firstbrain

AI-powered animation tool for creating motion in logos, UI, icons, and social media assets.

BEKO2210/Firstbrain

Best practices for Remotion - Video creation in React

BEKO2210/Firstbrain

Generate walkthrough videos from Stitch projects using Remotion with smooth transitions, zooming, and text overlays

BEKO2210/Firstbrain

Seek and analyze video content using Memories.ai Large Visual Memory Model for persistent video intelligence

BEKO2210/Firstbrain

Writes complete, structured landing pages optimized for SEO ranking, AEO citation, and visitor conversion. Activate when the user wants to write or generate a landing page for a product, service, or offer.

BEKO2210/Firstbrain

Automate TikTok tasks via Rube MCP (Composio): upload/publish videos, post photos, manage content, and view user profiles/stats. Always search tools first for current schemas.

BEKO2210/Firstbrain

Video and audio perception, indexing, and editing. Ingest files/URLs/live streams, build visual/spoken indexes, search with timestamps, edit timelines, add overlays/subtitles, generate media, and create real-time alerts.

BEKO2210/Firstbrain

Upload, stream, search, edit, transcribe, and generate AI video and audio using the VideoDB SDK.

BEKO2210/Firstbrain

One sentence - what this skill does and when to invoke it

BEKO2210/Firstbrain

Automate YouTube tasks via Rube MCP (Composio): upload videos, manage playlists, search content, get analytics, and handle comments. Always search tools first for current schemas.

BEKO2210/Firstbrain

Extract transcripts from YouTube videos and generate comprehensive, detailed summaries using intelligent analysis frameworks

相关技能