Welcome to tween.js
tween.js is a simple and fast JavaScript (and TypeScript) tweening engine for easy animations, incorporating optimised Robert Penner's equations. It does one thing and does it well: tweening the properties of an object from a starting value to an ending value over a specific duration.
It's lightweight, dependency-free, and doesn't dictate your project's structure, making it incredibly flexible for integration into any animation loop.
Key Features
- Focused: Does one thing only—tweens properties of an object.
- Flexible: Doesn't create its own animation loop, allowing it to be integrated into any rendering engine (like Three.js) or custom
requestAnimationFrame
loop. - Powerful: Supports chaining, delaying, repeating, and reversing tweens.
- Extensible: Comes with a suite of standard easing functions but also supports custom easing functions.
- Modern: Written in TypeScript and distributed in multiple module formats (ESM, CJS, UMD).
A Simple Example
Here's a quick look at how to animate an object's coordinates and apply the changes to a DOM element.
<div id="box"></div>
<style>
#box {
background-color: deeppink;
width: 100px;
height: 100px;
}
</style>
<script type="module">
import {Tween, Easing, update} from 'https://unpkg.com/@tweenjs/tween.js@25.0.0/dist/tween.esm.js'
const box = document.getElementById('box');
const coords = {x: 0, y: 0};
const tween = new Tween(coords)
.to({x: 300, y: 200}, 1000)
.easing(Easing.Quadratic.InOut)
.onUpdate(() => {
box.style.setProperty('transform', `translate(${coords.x}px, ${coords.y}px)`)
})
.start();
function animate(time) {
update(time);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
This code creates a tween that animates the coords
object from {x: 0, y: 0}
to {x: 300, y: 200}
over one second, using a smooth easing function. The onUpdate
callback applies these changing coordinates to a div
's CSS transform property, moving it across the screen.