How to create timeline-based JavaScript animations with GreenSock Animation Platform (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, 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.

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.

[cc lang=”html”]

 


[/cc]

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. Files are also hosted on the super-fast Cloudflare CDN, so the simplest way is to use the hosted files like this:

[cc lang=”javascript”][/cc]

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:

[cc lang=”javascript”]// 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});[/cc]

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:

[cc lang=”javascript”]tweenMax.from(“.logo”,2,{x:400});[/cc]

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:
[cc lang=”javascript”]
TweenMax.fromTo(“.logo”,2,{x:400},{x:200});[/cc]

05. Easing

greenshock animation ease visualizer

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:

[cc lang=”javascript”]TweenMax.to(“.logo”,2,{x:100, y:100, rotation:90, ease:Circ.easeIn});[/cc]

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:

[cc lang=”javascript”]// 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});[/cc]

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:

[cc lang=”javascript”]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});[/cc]

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:

[cc lang=”javascript”]TweenMax.to(“.logo”,1,{
y:100,
ease:Bounce.easeOut,
onComplete:tweenComplete
});
function tweenComplete() {
console.log(“tween complete”);
}[/cc]

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:

[cc lang=”javascript”]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);
}[/cc]

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:

[cc lang=”javascript”]// 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); [/cc]

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:

[cc lang=”javascript”]TweenMax.to(“.logo”, 3, {
x:100,
y:100,
scale:1.5,
rotationY:360 ,
ease:Bounce.easeOut });[/cc]

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:

[cc lang=”javascript”]//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” );[/cc]

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:

[cc lang=”javascript”]var tl = new TimelineMax({
// repeat infinitely
repeat:-1,
yoyo:true, });[/cc]

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:

[cc lang=”javascript”]// 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);[/cc]

We read it on creativebloq

Recent Articles

Angular 9 Next Versions: Ivy, Bazel and more

Angular 9 next versions are here. Besides updates to Ivy, the update includes three features for the Language Service and Service Worker and changes...

Google Releases Dart 2.5: Code Completion through Machine Learning

The latest version of Googles C-Alternative, Go 1.13, is barely released, as the JavaScript derivative of the Internet giant follows: Dart 2.5 is here!...

Laravel 6.0 is here: Support for Serverless Platform Laravel Vapor

A new update is available for the framework Laravel. Laravel 6.0 is compatible with Laravel Vapor, a serverless deployment platform. The development team has...

Microsoft’s FaaS service Azure Functions: Now with Python support

Azure Functions has received support for Python: Microsoft's FaaS service can host Python workloads for data science, machine learning, and more. So far, the...

On the way to Angular 9: Three bugfixes in Angular 9

With Angular 9.0.0-next.1 there is a second Next-Release available for Angular 9, which can now be tested. The number of changes to the version...

Related Stories

1 Comment

Leave A Reply

Please enter your comment!
Please enter your name here