Top Related Projects
GSAP (GreenSock Animation Platform), a JavaScript animation library for the modern web
JavaScript animation engine
A simple but powerful tweening / animation library for Javascript. Part of the CreateJS suite of libraries.
The fastest TypeScript animation engine on the web
The motion graphics toolbelt for the web
Quick Overview
Tween.js is a lightweight JavaScript library for creating smooth animations. It allows developers to easily create and manage tweens, which are gradual transitions between two states over time. Tween.js is widely used for creating animations in web applications and games.
Pros
- Simple and intuitive API for creating animations
- Lightweight and performant, with minimal overhead
- Supports various easing functions for different animation effects
- Can be used with any JavaScript framework or vanilla JavaScript
Cons
- Limited to numeric property animations (doesn't support color or path animations natively)
- Lacks some advanced features found in larger animation libraries
- Requires manual updating of tweens in animation loops
- No built-in timeline functionality for complex animation sequences
Code Examples
Creating a simple tween:
const box = document.querySelector('.box');
const tween = new TWEEN.Tween({ x: 0 })
.to({ x: 300 }, 1000)
.onUpdate((obj) => {
box.style.transform = `translateX(${obj.x}px)`;
})
.start();
Using easing functions:
const bounce = new TWEEN.Tween({ y: 0 })
.to({ y: 200 }, 1000)
.easing(TWEEN.Easing.Bounce.Out)
.onUpdate((obj) => {
ball.style.transform = `translateY(${obj.y}px)`;
});
Chaining tweens:
const rotateAndScale = new TWEEN.Tween({ rotation: 0, scale: 1 })
.to({ rotation: 360, scale: 2 }, 1000)
.onUpdate((obj) => {
element.style.transform = `rotate(${obj.rotation}deg) scale(${obj.scale})`;
})
.chain(
new TWEEN.Tween({ scale: 2 })
.to({ scale: 1 }, 500)
.onUpdate((obj) => {
element.style.transform = `scale(${obj.scale})`;
})
);
Getting Started
-
Install Tween.js using npm:
npm install @tweenjs/tween.js
-
Import Tween.js in your project:
import * as TWEEN from '@tweenjs/tween.js';
-
Create and start a tween:
const tween = new TWEEN.Tween({ x: 0 }) .to({ x: 100 }, 1000) .onUpdate((obj) => { console.log(obj.x); }) .start();
-
Update tweens in your animation loop:
function animate(time) { requestAnimationFrame(animate); TWEEN.update(time); } requestAnimationFrame(animate);
Competitor Comparisons
GSAP (GreenSock Animation Platform), a JavaScript animation library for the modern web
Pros of GSAP
- More feature-rich with advanced animation capabilities
- Better performance, especially for complex animations
- Extensive documentation and community support
Cons of GSAP
- Larger file size, which may impact load times
- Steeper learning curve due to its extensive feature set
- Commercial license required for some use cases
Code Comparison
GSAP:
gsap.to(".box", {duration: 2, x: 100, y: 50, rotation: 360});
Tween.js:
new TWEEN.Tween({x: 0, y: 0, rotation: 0})
.to({x: 100, y: 50, rotation: 360}, 2000)
.onUpdate(function(obj) {
box.style.transform = `translate(${obj.x}px, ${obj.y}px) rotate(${obj.rotation}deg)`;
})
.start();
Summary
GSAP offers more advanced features and better performance, making it suitable for complex animations. However, it comes with a larger file size and potential licensing costs. Tween.js is lighter and simpler, making it a good choice for basic animations or projects with size constraints. The code comparison shows that GSAP provides a more concise syntax for common animation tasks, while Tween.js requires more manual setup but offers fine-grained control over the animation process.
JavaScript animation engine
Pros of anime
- More comprehensive animation features, including SVG morphing and timeline control
- Easier to create complex animations with less code
- Better performance for large-scale animations due to its optimized engine
Cons of anime
- Larger file size compared to tween.js
- Steeper learning curve for beginners due to more advanced features
- Less flexibility for custom easing functions
Code Comparison
anime:
anime({
targets: '.element',
translateX: 250,
rotate: '1turn',
duration: 800,
easing: 'easeInOutQuad'
});
tween.js:
new TWEEN.Tween({ x: 0, rotation: 0 })
.to({ x: 250, rotation: Math.PI * 2 }, 800)
.easing(TWEEN.Easing.Quadratic.InOut)
.onUpdate(function(object) {
element.style.transform = `translateX(${object.x}px) rotate(${object.rotation}rad)`;
})
.start();
The code comparison shows that anime provides a more concise and declarative approach to creating animations, while tween.js offers more granular control over the animation process. anime's syntax is generally easier to read and write, especially for complex animations, but tween.js allows for more fine-tuned manipulation of individual properties during the animation.
A simple but powerful tweening / animation library for Javascript. Part of the CreateJS suite of libraries.
Pros of TweenJS
- Part of the larger CreateJS suite, offering integration with other libraries
- Provides a timeline feature for sequencing multiple tweens
- Supports tweening of both numeric and non-numeric properties
Cons of TweenJS
- Larger file size due to being part of the CreateJS ecosystem
- Less frequent updates compared to tween.js
- More complex API, which may have a steeper learning curve
Code Comparison
TweenJS:
createjs.Tween.get(target)
.to({x: 300, y: 200}, 1000, createjs.Ease.elasticOut)
.call(handleComplete);
tween.js:
new TWEEN.Tween(target)
.to({x: 300, y: 200}, 1000)
.easing(TWEEN.Easing.Elastic.Out)
.onComplete(handleComplete)
.start();
Both libraries offer similar functionality for creating tweens, but TweenJS uses a more chainable approach with the get()
method, while tween.js creates a new instance for each tween. TweenJS also includes easing functions directly in its API, whereas tween.js separates them into a distinct TWEEN.Easing
object.
The fastest TypeScript animation engine on the web
Pros of Shifty
- More lightweight and focused on core tweening functionality
- Better TypeScript support with built-in type definitions
- Offers a more flexible easing system with custom easing function support
Cons of Shifty
- Less mature and less widely adopted compared to Tween.js
- Fewer built-in features and utilities for complex animations
- Smaller community and ecosystem around the library
Code Comparison
Tween.js:
new TWEEN.Tween({ x: 0 })
.to({ x: 100 }, 1000)
.easing(TWEEN.Easing.Quadratic.Out)
.onUpdate((object) => console.log(object.x))
.start();
Shifty:
shifty.tween({
from: { x: 0 },
to: { x: 100 },
duration: 1000,
easing: 'quadratic-out',
step: (state) => console.log(state.x)
});
Both libraries offer similar core functionality for creating and managing tweens. Tween.js has a more object-oriented approach, while Shifty uses a more functional style. Shifty's API is generally more concise, but Tween.js offers more built-in features and options for complex animations.
The motion graphics toolbelt for the web
Pros of mojs
- More comprehensive animation toolkit with built-in shape and burst modules
- Declarative API for creating complex animations with less code
- Better performance for complex animations due to optimized rendering
Cons of mojs
- Steeper learning curve due to its more extensive feature set
- Larger file size, which may impact load times for smaller projects
- Less frequent updates and potentially less community support
Code Comparison
mojs:
const burst = new mojs.Burst({
radius: { 0: 100 },
count: 5,
children: {
shape: 'circle',
fill: { 'cyan' : 'yellow' },
duration: 2000
}
});
tween.js:
const tween = new TWEEN.Tween({ radius: 0 })
.to({ radius: 100 }, 2000)
.easing(TWEEN.Easing.Quadratic.Out)
.onUpdate(function(object) {
// Manual update of object properties
});
mojs provides a more concise and declarative way to create complex animations, while tween.js requires more manual setup and updating of object properties. mojs includes built-in shape modules, whereas tween.js focuses solely on tweening values and leaves rendering to the developer.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
tween.js
JavaScript (TypeScript) tweening engine for easy animations, incorporating optimised Robert Penner's equations.
More languages: English, ç®ä½ä¸æ
<div id="box"></div>
<style>
#box {
background-color: deeppink;
width: 100px;
height: 100px;
}
</style>
<script type="module">
import {Tween, Easing} from 'https://unpkg.com/@tweenjs/tween.js@23.1.3/dist/tween.esm.js'
const box = document.getElementById('box') // Get the element we want to animate.
const coords = {x: 0, y: 0} // Start at (0, 0)
const tween = new Tween(coords, false) // Create a new tween that modifies 'coords'.
.to({x: 300, y: 200}, 1000) // Move to (300, 200) in 1 second.
.easing(Easing.Quadratic.InOut) // Use an easing function to make the animation smooth.
.onUpdate(() => {
// Called after tween.js updates 'coords'.
// Move 'box' to the position described by 'coords' with a CSS translation.
box.style.setProperty('transform', 'translate(' + coords.x + 'px, ' + coords.y + 'px)')
})
.start() // Start the tween immediately.
// Setup the animation loop.
function animate(time) {
tween.update(time)
requestAnimationFrame(animate)
}
requestAnimationFrame(animate)
</script>
Features
- Does one thing only and does it well: tweens properties of an object
- Doesn't take care of CSS units (e.g. appending
px
) - Doesn't interpolate colors
- Easing functions are reusable outside of Tween
- Can also use custom easing functions
- Doesn't make its own animation loop, making it flexible for integration into any animation loop.
Examples
hello world (source) |
Bars (source) |
||
Black and red (source) |
Graphs (source) |
||
Simplest possible example (source) |
Video and time (source) |
||
Array interpolation (source) |
Dynamic to, object (source) |
||
Dynamic to, interpolation array (source) |
Dynamic to, large interpolation array (source) |
||
Repeat (source) |
Relative values (source) |
||
Yoyo (source) |
Stop all chained tweens (source) |
||
Custom functions (source) |
Relative start time (source) |
||
Pause tween (source) |
Complex properties (source) |
||
Animate an array of values (source) |
Installation
The recommended method is to use import
syntax. Here we've listed various
install methods starting roughly with the most recommended first and least
desirable last. Evaluate all of the following methods to pick what is most
suitable for your project.
With npm install
and import
from node_modules
You can add tween.js as an npm dependency:
npm install @tweenjs/tween.js
Without a build tool
Installed locally
You can import from node_modules
if you serve node_modules
as part of your
website, using a standard importmap
script tag. First, assuming node_modules
is at the root of your website, you can write an import map like so in your HTML
file:
<script type="importmap">
{
"imports": {
"@tweenjs/tween.js": "/node_modules/@tweenjs/tween.js/dist/tween.esm.js"
}
}
</script>
Now in any of your module scripts you can import Tween.js by its package name:
<script type="module">
import {Tween} from '@tweenjs/tween.js'
</script>
Import from CDN
Note that, without the importmap
, you can import directly from a CDN as with the first example above, like so:
<script type="module">
import {Tween} from 'https://unpkg.com/browse/@tweenjs/tween.js@23.1.3/dist/tween.esm.js'
</script>
You can also link your importmap
to the CDN instead of a local node_modules
folder, if you prefer that:
<script type="importmap">
{
"imports": {
"@tweenjs/tween.js": "https://unpkg.com/browse/@tweenjs/tween.js@23.1.3/dist/tween.esm.js"
}
}
</script>
<script type="module">
import {Tween} from '@tweenjs/tween.js'
</script>
With a build tool
If you are using Node.js,
Parcel, Webpack,
Rollup, Vite, or another build
tool, then you can install @tweenjs/tween.js
with npm install @tweenjs/tween.js
, and import
the library into your JavaScript (or
TypeScript) file, and the build tool will know how to find the source code from
node_modules
without needing to create an importmap
script:
import * as TWEEN from '@tweenjs/tween.js'
However, note that this approach requires always running a build tool for your
app to work, while the importmap
approach will simply work without any build
tools as a simple static HTML site.
Manual build
Another approach is to download the source code with git, manually build the library, then place the output in your project. Node.js is required for this.
git clone https://github.com/tweenjs/tween.js
cd tween.js
npm install
npm run build
This will create some builds in the dist
directory. There are currently two different builds of the library:
- ES6 Module in
/dist/tween.esm.js
(recommended) - UMD in
/dist/tween.umd.js
(deprecated, will be removed in a future major version)
You are now able to copy one of those two files into your project, and use like this (recommended):
<script type="module">
import {Tween} from 'path/to/tween.esm.js'
</script>
or (deprecated, to be removed in future major):
<script src="path/to/tween.umd.js"></script>
<script>
const {Tween} = TWEEN
</script>
where path/to
is replaced with the location where you placed the file.
[!Note] You can also download these files from unpkg, for example here: https://unpkg.com/browse/@tweenjs/tween.js@23.1.3/dist/
Global variable from CDN (deprecated)
[!Note] This method is deprecated and will be removed in a future major version!
Install a global TWEEN
variable from a content-delivery network (CDN) using the UMD file.
From cdnjs:
<script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/23.1.3/tween.umd.js"></script>
Or from unpkg.com:
<script src="https://unpkg.com/@tweenjs/tween.js@^23.1.3/dist/tween.umd.js"></script>
Then use the TWEEN
variable in any script:
<script>
const {Tween, Easing, Group /*, ...*/} = TWEEN
const tween = new Tween(someObject)
// ...
</script>
[!Note] unpkg.com supports a semver version in the URL, where the
^
in the URL tells unpkg to give you the latest version 20.x.x.
CommonJS (deprecated)
Skip this section if you don't know what CommonJS is!
[!Note] This method is deprecated and will be removed in a future major version!
Any of the above methods work in older systems that still use CommonJS. Repeat
any of the above methods but using dist/tween.cjs
instead of
dist/tween.esm.js
or dist/tween.umd.js
.
Documentation
- User guide
- Contributor guide
- Tutorial using tween.js with three.js
- Also: libtween, a port of tween.js to C by jsm174
Tests
You need to install npm
first--this comes with node.js, so install that one first. Then, cd to tween.js
's (or wherever you cloned the repo) directory and run:
npm install
To run the tests run:
npm test
If you want to add any feature or change existing features, you must run the
tests to make sure you didn't break anything else. Any pull request (PR) needs
to have updated passing tests for feature changes (or new passing tests for new
features or fixes) in src/tests.ts
to be accepted. See
contributing for more information.
People
Maintainers: Joe Pea (@trusktr).
Projects using tween.js
Top Related Projects
GSAP (GreenSock Animation Platform), a JavaScript animation library for the modern web
JavaScript animation engine
A simple but powerful tweening / animation library for Javascript. Part of the CreateJS suite of libraries.
The fastest TypeScript animation engine on the web
The motion graphics toolbelt for the web
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot