Get started with GreenSock Animation Platform
Learn how to create timeline-based JavaScript animations with GSAP.
GreenSock Animation Platform (GSAP) enables you to animate anything you can access with JavaScript including DOM, Canvas and CSS, as well as your own custom objects.
GSAP also helps resolve browser inconsistencies for easier user testing (good web hosting can help here, too), enables you to use objects to manage complex animations, and runs up to 20 times faster than jQuery. It has become a standard in the industry, and has been used in countless award-winning websites. Got a site to build? Here's our guide to the best website builder around.
01. Set up a basic HTML file
The best way to learn GSAP is to see it in action. In this tutorial you'll learn about the key features of the platform with working examples that you can put to use in your projects today!
Get started by setting up a basic HTML file, where you can drop in your JavaScript code. Include an image with a logo class. You'll use GSAP to animate properties to see how it works.
<html lang="en">
<head>
<style>
.logo { width:150px; }
</style>
</head>
<body>
<img class="logo"
src="logo.svg" />
<script>
// code here
</script>
</body>
</html>
02. Include GSAP Library
Next, you'll need to add GSAP to your web project. Between your <image> and <script> tags, insert a link to the GSAP library. You can download the ZIP directly from here,or grab it from GitHub (if you've got files to share, choose the perfect cloud storage). Files are also hosted on the super-fast Cloudflare CDN, so the simplest way is to use the hosted files like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.0.1/TweenMax.min.js"></script>
03. Animate with tweening
Tweening is the process of changing a value over time to create an animation. For example, moving an object from A to B, scaling it, or rotating it. You can also tween your own custom values.
The simplest way to tween a property is to use the TweenMax.to() function. This needs a target object, a duration and the property/value pairs you are animating. To see the function in action, try out each of the lines of code below using the logo as the target object:
Get top Black Friday deals sent straight to your inbox: Sign up now!
We curate the best offers on creative kit and give our expert recommendations to save you time this Black Friday. Upgrade your setup for less with Creative Bloq.
// tween x position from current
to 400 over 2 seconds
TweenMax.to(".logo",2,{x:400});
// tween y position from current
to 200 and opacity to 0, over 1
second
TweenMax.to(".logo",1,{y:200, opacity:0});
// tween x and y to 100, scale to
1.5, and rotate 90 deg, over 2
second
TweenMax.to(".logo",2,{x:100, y:100, scale:1.5, rotation:90});
04. Tween from and FromTo
You can tween a property from its current value to a new one using to(), but you can also tween from a value to its current value. For example, if your logo is starting at x position 0 and you want it to end there, you could do this:
tweenMax.from(".logo",2,{x:400});
In this case, your logo will immediately move to x=400 and then tween to x=0. You can even define both the start and end values, ignoring the current values using fromTo() like this:
TweenMax.fromTo(".logo",2,{x:400},{x:200});
05. Easing
Easing is the 'style' of animation, as values transition from A to B. Instead of a constant rate of speed, which is called 'linear', you can apply functions to curve the rate of speed. Do they start slowly and gradually speed up? Do they come to an abrupt stop and bounce a little at the end? In animation these styles add character and emotion to your work. You can apply an easing function like this:
TweenMax.to(".logo",2,{x:100, y:100, rotation:90, ease:Circ.easeIn});
06. Easing functions and In/Out
GSAP includes a variety of easing functions, such as back, bounce, elastic, sin, circ, and expo. You may have also noticed that the ease function has a property of easeIn, which we used in the step above. You can also use easeOut and easeInOut. These indicate where the easing curve is applied in the animation. Try out the following to see the results:
// easing Out with a bounce
TweenMax.to(".logo",2,{x:100, y:100, rotation:90, ease:Bounce.easeOut});
// easing In and Out with elastic
TweenMax.to(".logo",2,{x:100, y:100, rotation:90, ease:Elastic.easeInOut});
07. Delay a tween
Sometimes you will want to delay the start of an animation, either to synchronise it with another animation, or to make it wait for an event to occur. You can use another one GSAP's special properties called delay to do this. Try out the following code to see how you can delay tweens for specific timing:
TweenMax.to(".logo",1,{y:100, ease:Bounce.easeOut});
// delay this tween by 1 sec
TweenMax.to(".logo",1,{rotation:90, ease:Circ.easeOut,delay:1});
08. Callback functions
To integrate animations with your code, it's important to know when events occur, especially when an animation ends or begins. You can use the onComplete event callback for this. You may want to know when a tween starts, using onStart. And you may also want to sync your tween with another animation, or use the tween and its easing to update some other custom object. Use the onUpdate callback for this. Here is how you use the callback:
TweenMax.to(".logo",1,{
y:100,
ease:Bounce.easeOut,
onComplete:tweenComplete
});
function tweenComplete() {
console.log("tween complete");
}
09. Callback parameters
When firing callbacks you may want to pass information along with the callback to the function that handles it. You may need to pass information about the caller or specific values. This enables you to integrate your animations with the rest of your code base. All parameters are passed via callback+"Params", that is onUpdateParams.
In the following example, you can track progress of the tween using the keyword {self} and can see how to pass multiple parameters using an array:
TweenMax.to(".logo",1,{
y:100,
ease:Bounce.easeOut,
onUpdate: tweenUpdate,
onUpdateParams:["{self}",
"completed"]
});
function tweenUpdate(tween,
message) {
var percentage = tween.
progress() * 100; // progress()
is a value 0-1
console.log(percentage +
" " + message);
}
10. Controlling animations
Okay, so you can now create tweens and ease the tweens, fire callbacks and parameters. But how do you control animations? Often you want to start or stop them based on other events.
If you need to stop an animation you can use the pause() method. If you want to resume a tween, use resume(). To totally destroy a tween use kill(). Try out the following and see what happens:
// var to hold reference to tween
var tween = TweenMax.to(".
logo",2,{ y:100, ease:Bounce.
easeOut });
// pause immediately
tween.pause();
// start on event
setTimeout(function(){tween.
resume()},1000);
// reverse animation on event
setTimeout(function(){tween.
reverse()},3000);
11. CSS and CSSPlugin
The CSSPlugin is included when you use TweenMax. It is a huge time-saver, in that it normalises behaviours across browsers and auto-detects when it is needed for animations. CSSPlugin can handle colour tweens, SVG animations and optimised performance with caching and other internal tricks – and it's often more efficient to translate positions via CSS.
You've already seen this in action when you used the opacity and position animations. It works without any special coding!
12. 2D and 3D transforms
CSS transformations enable you to scale, rotate translate and skew. They work in both 2D and 3D to create beautiful effects quickly. GSAP includes built-in transform properties such as x, y, rotation, rotationX, rotationY, skewX and scale. Try applying the following tween to your image instead of the ones we've already tried:
TweenMax.to(".logo", 3, {
x:100,
y:100,
scale:1.5,
rotationY:360 ,
ease:Bounce.easeOut });
13. Timelines
Once you move beyond one or two tweens you may be wondering how to manage multiple animations. GSAP includes a timeline object to do exactly that. You append tweens to the timeline object and can use the position parameter after the tween to time them. You can have tweens run one after another, or have gaps, or even overlap them. Add a couple more images to your HTML with classes logo2 and logo3 respectively.
To see how it works, try out the following timeline code:
//create a timeline instance
var tl = new TimelineMax();
tl.add( TweenMax.to(".logo", 1,
{x:50}) );
// note the final "0" to make
this one start at 0 sec.
tl.add( TweenMax.to(".logo2", 1,
{y:100} ),"0" );
//note the "+.25" to make this
one start at .25 sec
tl.add( TweenMax.to(".logo3", 1,
{rotationY:180, y:50,
X:50}),"+.25" );
14. Timeline control
As well as controlling animations, you may want to control timelines, too. Luckily, you can pause, resume and reverse just like you can with animations. You can also add parameters to the timeline to repeat, yoyo and add callbacks for the entire timeline. You can also control a timeline's speed using the timeScale property. Try replacing your timeline declaration with the following code to see how it works:
var tl = new TimelineMax({
// repeat infinitely
repeat:-1,
yoyo:true, });
15. Get and set properties
One feature that's really useful is getting and setting properties of tweens and timelines. That way, you can get to know the overall progress and duration, or gather other information, about a GSAP object. In this code example you can get the duration of the timeline, and then set its duration to change it. This works the same for tweens as well. It's another great way to react in real time to events, and modify animations on the fly. Add the following after your previous timeline code:
// get the current duration of
the timeline
console.log(tl.duration());
//sets the duration to 5 seconds
after a 2 sec wait
setTimeout(function(){
tl.duration(5);
}, 2000);
This article was originally published in creative web design magazine Web Designer. Buy issue 279 or subscribe.
Read more:
Thank you for reading 5 articles this month* Join now for unlimited access
Enjoy your first month for just £1 / $1 / €1
*Read 5 free articles per month without a subscription
Join now for unlimited access
Try first month for just £1 / $1 / €1
Richard is an award-winning interactive technologist, designer and developer. He specialises in creating interactive worlds with science-fiction themes, exploring the synergy between human and machine. He has also written regular articles for Net Magazine, and Web Designer Magazine on a range of exciting topics across the world of tech, including artificial intelligence, VFX, 3D and more.
Related articles
- How Nekki is designing "visually striking" boss characters for video game SPINE
- How AI was used to create 'melty' VFX transitions in Here, the millennium spanning movie starring Tom Hanks
- 2D art of the week: Deborah Saez
- Creating SPINE's cinematic gameplay is like making an "action movie within a game"