首页
/ TweenJS 使用教程

TweenJS 使用教程

2026-01-17 08:24:21作者:董灵辛Dennis

项目介绍

TweenJS 是一个简单而强大的 JavaScript 动画库,主要用于创建平滑的补间动画。它支持各种缓动函数,可以轻松地与 CreateJS 生态系统中的其他库(如 EaselJS)集成。TweenJS 的设计目标是提供一个轻量级的、易于使用的动画引擎,适用于各种 Web 项目。

项目快速启动

安装

你可以通过 npm 安装 TweenJS:

npm install @tweenjs/tween.js

或者直接在 HTML 文件中引入:

<script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/18.6.4/tween.min.js"></script>

基本使用

以下是一个简单的示例,展示如何使用 TweenJS 创建一个对象的动画:

// 引入 TweenJS
import { Tween, update } from '@tweenjs/tween.js';

// 定义一个对象
const position = { x: 0, y: 0 };

// 创建一个补间动画
const tween = new Tween(position)
  .to({ x: 100, y: 100 }, 1000) // 1秒内移动到 (100, 100)
  .easing(Tween.Easing.Quadratic.Out) // 使用缓动函数
  .onUpdate(() => {
    console.log(position.x, position.y); // 更新时输出位置
  })
  .start(); // 启动动画

// 在 requestAnimationFrame 中更新动画
function animate() {
  requestAnimationFrame(animate);
  update(); // 更新所有补间动画
}

animate();

应用案例和最佳实践

案例1:简单的位置动画

const box = document.getElementById('box');
const position = { x: 0, y: 0 };

const tween = new Tween(position)
  .to({ x: 300, y: 200 }, 2000)
  .easing(Tween.Easing.Quadratic.Out)
  .onUpdate(() => {
    box.style.transform = `translate(${position.x}px, ${position.y}px)`;
  })
  .start();

function animate() {
  requestAnimationFrame(animate);
  update();
}

animate();

案例2:链式动画

const position = { x: 0 };

const tween1 = new Tween(position)
  .to({ x: 100 }, 1000)
  .onComplete(() => {
    console.log('Tween 1 completed');
  });

const tween2 = new Tween(position)
  .to({ x: 0 }, 1000)
  .onComplete(() => {
    console.log('Tween 2 completed');
  });

tween1.chain(tween2);
tween1.start();

function animate() {
  requestAnimationFrame(animate);
  update();
}

animate();

典型生态项目

CreateJS

TweenJS 是 CreateJS 生态系统的一部分,CreateJS 是一组用于构建丰富的交互式内容的 JavaScript 库。除了 TweenJS,CreateJS 还包括以下库:

  • EaselJS:用于处理 HTML5 Canvas 上的图形和交互。
  • SoundJS:用于处理音频播放和管理。
  • PreloadJS:用于预加载资源,如图像、声音和数据。

这些库可以相互配合,提供完整的 Web 动画和交互解决方案。

Three.js

TweenJS 也可以与 Three.js 结合使用,Three.js 是一个用于在 Web 上创建 3D 图形的库。通过 TweenJS,可以轻松地为 Three.js 中的 3D 对象创建动画。

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(
登录后查看全文
热门项目推荐
相关项目推荐