Quick Start Guide
This guide will walk you through creating a simple animation from scratch. We'll animate a box moving across the screen.
The HTML File
Create a file named index.html and add the following code. This sets up a basic webpage with a div element that we will animate.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>tween.js - Quick Start</title>
<style>
#box {
position: relative;
width: 100px;
height: 100px;
background-color: #88ddff;
}
</style>
</head>
<body>
<div id="box"></div>
<!-- 1. Import tween.js using a script tag with type="module" -->
<script type="module">
// 2. Import the necessary components from the library
import { Tween, Easing, update } from 'https://unpkg.com/@tweenjs/tween.js@25.0.0/dist/tween.esm.js';
// 3. Get a reference to the DOM element we want to animate
const box = document.getElementById('box');
// 4. Create an object to store the properties we want to animate.
// This object's properties will be modified by the tween.
const coords = { x: 0 };
// 5. Create the Tween. We pass it the 'coords' object because that's
// the object we want to modify.
const tween = new Tween(coords)
.to({ x: 400 }, 1000) // Animate 'x' to 400 over 1000 milliseconds
.easing(Easing.Quadratic.Out) // Use a smooth easing function
.onUpdate(() => {
// 6. This function is called every time the tween updates.
// We use the new 'coords.x' value to update the box's position.
box.style.transform = `translateX(${coords.x}px)`;
})
.start(); // 7. Start the tween immediately
// 8. Set up the animation loop.
function animate(time) {
update(time); // This function updates all active tweens
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
How It Works
- Import tween.js: We load the library as an ES module directly from a CDN.
- Import Components: We import
Tweento create animations,Easingfor smooth transitions, andupdateto run the animations. - Select Element: We get the
<div id="box">element that we will move. - Create State Object:
tween.jsworks by modifying the properties of a plain JavaScript object. We createcoordswith anxproperty to represent the box's horizontal position. - Create a Tween: We instantiate a
new Tween(), telling it which object to animate (coords). We then chain methods to configure it:.to({ x: 400 }, 1000): Defines the target state. We want thexproperty to become400over a duration of1000milliseconds..easing(Easing.Quadratic.Out): Specifies the animation's timing function to make it feel more natural..onUpdate(...): This is our callback function. It runs on every frame of the animation. Inside, we apply the updatedcoords.xvalue to the box's CSStransformproperty..start(): This starts the animation.
- The Animation Loop:
tween.jsdoes not have its own internal loop. You must call itsupdate()function within your own animation loop. We create a standardanimatefunction usingrequestAnimationFramefor smooth, efficient rendering.