Jump to content
Search Community

Getting Started with GSAP - GSAP 2


| GreenSock
1223836

Note: This page was created for GSAP version 2. We have since released GSAP 3 with many improvements. While it is backward compatible with most GSAP 2 features, some parts may need to be updated to work properly. We encourage you to use the updated "Getting Started" page .

The GreenSock Animation Platform (GSAP) animates anything JavaScript can touch (CSS properties, SVG, React, canvas, generic objects, whatever) and solves countless browser inconsistencies, all with blazing speed (up to 20x faster than jQuery). See "Why GSAP?" to learn why it's used by over 8,000,000 sites and every major brand.

Hang in there through the learning curve and you'll discover how addictive animating with code can be. We promise it's worth your time.

Quick links

We'll cover the most popular features here but keep the GSAP docs handy for all the details.

First, let's talk about what GSAP actually does...

GSAP as a property manipulator

Animation ultimately boils down to changing property values many times per second, making something appear to move, fade, spin, etc. GSAP snags a starting value, an ending value and then interpolates between them 60 times per second.

For example, changing the x coordinate of an object from 0 to 1000 over the course of 1 second makes it move quickly to the right. Gradually changing opacity from 1 to 0 makes an element fade out. Your job as an animator is to decide which properties to change, how quickly, and the motion's "style" (known as easing - we'll get to that later).

To be technically accurate we could have named GSAP the "GreenSock Property Manipulator" (GSPM) but that doesn't have the same ring. ;)

DOM, SVG, <canvas>, and beyond

GSAP doesn't have a pre-defined list of properties it can handle. It's super flexible, adjusting to almost anything you throw at it. GSAP can animate all of the following:

  • CSS: 2D and 3D transforms, colors, width, opacity, border-radius, margin, and almost every CSS value (with the help of CSSPlugin).
  • SVG attributes: viewBox, width, height, fill, stroke, cx, r, opacity, etc. Plugins like MorphSVG and DrawSVG can be used for advanced effects.
  • Any numeric value For example, an object that gets rendered to an HTML5 <canvas>. Animate the camera position in a 3D scene or filter values. GSAP is often used with Three.js and Pixi.js.

Once you learn the basic syntax you'll be able to use GSAP anywhere JavaScript runs. This guide will focus on the most popular use case: animating CSS properties of DOM elements. (Note: if you're using React, read this too.)

If you're using any of the following frameworks, these articles may help:

What's GSAP Exactly?

GSAP is a suite of tools for scripted animation. It includes:

Loading GSAP

CDN

The simplest way to load GSAP is from the CDN with a <script> tag. TweenMax (and all publicly available GSAP files) are hosted on Cloudfare's super-fast and reliable cdnjs.com.

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.3/TweenMax.min.js"></script>

Banner Ad CDNs

Every major ad network excludes GSAP from file size limits when you load it from their CDN! Contact your ad network for their URLs. For example, Google hosts TweenMax at:

//AdWords and DoubleClick ads only
"https://s0.2mdn.net/ads/studio/cached_libs/tweenmax_2.1.2_min.js"

NPM

npm install gsap

See the NPM Usage page in the docs for a full guide including how to import things (ES modules or UMD format), tree shaking, Webpack, how to get bonus plugins into a build system, etc.

Downloading GSAP

Download a zip directly from our home page or your account dashboard. If you're logged in as a Club GreenSock member this zip will include your bonus plugins.

GitHub

View the source code on GitHub.

Tweening Basics

Let's start with TweenMax, GSAP's most popular tool. We'll use CodePen demos so that you can easily fork and edit each example right in your browser.

TweenMax.to()

To create an animation, TweenMax.to() needs 3 things:

  • target - the object you are animating. This can be a raw object, an array of objects, or selector text like ".myClass".
  • duration (in seconds)
  • vars - an object with property/value pairs that you're animating to (like opacity:0.5, rotation:45, etc.) and other optional special properties like onComplete.

For example, to move an element with an id of "logo" to an x position of 100 (same as transform: translateX(100px)) over the course of 1 second:

TweenMax.to("#logo", 1, {x:100});

Note: Remember that GSAP isn't just for DOM elements, so you could even animate custom properties of a raw object like this:

var obj = {prop:10};
TweenMax.to(obj, 1, {
  prop:200, 
  //onUpdate fires each time the tween updates; we'll explain callbacks later.
  onUpdate:function() {
    console.log(obj.prop); //logs the value on each update.
  }
});
cheat-sheet

Demo: TweenMax.to() Basic Usage

See the Pen TweenMax.to() Basic Usage by GreenSock (@GreenSock) on CodePen.

If you would like to edit the code and experiment with your own properties and values, just hit the Edit on CodePen button.

Notice that the opacity, scale, rotation and x values are all being animated in the demo above but DOM elements don't actually have those properties! In other words, there's no such thing as element.scale or element.opacity. How'd that work then? It's the magic of CSSPlugin. Before we talk about that, let's explain how plugins work in general.

Plugins

Think of plugins like special properties that get dynamically added to GSAP in order to inject extra abilities. This keeps the core engine small and efficient, yet allows for unlimited expansion. Each plugin is associated with a specific property name.

Among the most popular plugins are:

*loaded with TweenMax

CSSPlugin

In the previous example, CSSPlugin automatically noticed that the target is a DOM element, so it intercepted the values and did some extra work behind the scenes, applying them as inline styles (element.style.transform and element.style.opacity in that case). Be sure to watch the "Getting Started" video at the top of this article to see it in action.

CSSPlugin Features:

  • normalizes behavior across browsers and works around various browser bugs and inconsistencies
  • optimizes performance by auto-layerizing, caching transform components, preventing layout thrashing, etc.
  • controls 2D and 3D transform components (x, y, rotation, scaleX, scaleY, skewX, etc.) independently (eliminating order-of-operation woes)
  • reads computed values so you don't have to manually define starting values
  • animates complex values like borderRadius:"50% 50%" and boxShadow:"0px 0px 20px 20px red"
  • applies vendor-specific prefixes (-moz-, -ms-, -webkit-, etc.) when necessary
  • animates CSS Variables
  • handles color interpolation (rgb, rgba, hsl, hsla, hex)
  • normalizes behavior between SVG and DOM elements (particularly useful with transforms)
  • ...and lots more

Basically, CSSPlugin saves you a ton of headaches.

Because animating CSS properties is so common, GSAP automatically senses when the target is a DOM element and adds a css:{} wrapper. So internally, for example, {x:100, opacity:0.5, onComplete:myFunc} becomes {css:{x:100, opacity:0.5}, onComplete:myFunc}. That way, CSS-related values get routed to the plugin properly and you don't have to do any extra typing. You're welcome. ?

To understand the advanced capabilities of the CSSPlugin read the full CSSPlugin documentation.

2D and 3D transforms

CSSPlugin recognizes a number of short codes for transform-related properties:

GSAP CSS
x: 100 transform: translateX(100px)
y: 100 transform: translateY(100px)
rotation: 360 transform: rotate(360deg)
rotationX: 360 transform: rotateX(360deg)
rotationY: 360 transform: rotateY(360deg)
skewX: 45 transform: skewX(45deg)
skewY: 45 transform: skewY(45deg)
scale: 2 transform: scale(2, 2)
scaleX: 2 transform: scaleX(2)
scaleY: 2 transform: scaleY(2)
xPercent: 50 transform: translateX(50%)
yPercent: 50 transform: translateY(50%)

GSAP can animate any "transform" value but we strongly recommend using the shortcuts above because they're faster and more accurate (GSAP can skip parsing computed matrix values which are inherently ambiguous for rotational values beyond 180 degrees). The other major convenience GSAP affords is independent control of each component while delivering a consistent order-of-operation.

Performance note: it's much easier for browsers to update x and y (transforms) rather than top and left which affect document flow. So to move something, we recommend animating x and y.

Demo: Multiple 2D and 3D transforms

See the Pen Multiple 2D and 3D Transforms by GreenSock (@GreenSock) on CodePen.

Additional CSSPlugin notes

  • Be sure to camelCase all hyphenated properties. font-size should be fontSize, background-color should be backgroundColor.
  • When animating positional properties such as left and top, its imperative that the elements you are trying to move also have a css position value of absolute, relative or fixed.
  • vw/vh units aren't currently supported natively, but it's pretty easy to mimic using some JS like x: window.innerWidth * (50 / 100) where 50 is the vw. Just ask in the forums for some help.

from() tweens

Sometimes it's amazingly convenient to set up your elements where they should end up (after an intro animation, for example) and then animate from other values. That's exactly what TweenMax.from() is for.

For example, perhaps your "#logo" element currently has its natural x position at 0 and you create the following tween:

TweenMax.from("#logo", 1, {x:100});

The #logo will immediately jump to an x of 100 and animate to an x of 0 (or whatever it was when the tween started). In other words, it's animating FROM the values you provide to whatever they currently are.

Demo: TweenMax.from() with multiple properties

See the Pen TweenMax.from() tween by GreenSock (@GreenSock) on CodePen.

There is also a fromTo() method that allows you to define the starting values and the ending values:

//tweens from width 0 to 100 and height 0 to 200
TweenMax.fromTo("#logo", 1.5, {width:0, height:0}, {width:100, height:200});

Special properties (like onComplete)

A special property is like a reserved keyword that GSAP handles differently than a normal (animated) property. Special properties are used to define callbacks, delays, easing and more.

A basic example of a special property is delay:

TweenMax.to("#logo", 1, {x:100, delay:3});

This animation will have a 3-second delay before starting.

Other common special properties are:

  • onComplete - a callback that should be triggered when the animation finishes.
  • onUpdate - a callback that should be triggered every time the animation updates/renders
  • ease - the ease that should be used (like Power2.easeInOut)

Easing

If your animation had a voice, what would it sound like? Should it look playful? Robotic? Slick? Realistic? To become an animation rock star, you must develop a keen sense of easing because it determines the style of movement between point A and point B. The video below illustrates the basics.

An "ease" controls the rate of change during a tween. Below is an interactive tool that allows you to visually explore various eases. Note: you can click on the underlined parts of the code at the bottom to change things.

 

Use the ease special property:

TweenMax.to("#logo", 1, {x:300, ease:Bounce.easeOut});

Demo: Bounce Ease

See the Pen Special Properties: ease by GreenSock (@GreenSock) on CodePen.

See the Pen CustomEase Demo Explorer by GreenSock (@GreenSock) on CodePen.

For unprecedented control over your eases, be sure to check out CustomEase which allows you to literally draw any ease curve imaginable. CustomWiggle and CustomBounce are advanced eases that create extremely complex and realistic effects.

Callbacks

Callbacks invoke a function when a specific animation-related event occurs:

  • onComplete: called when the animation has completed.
  • onStart: called when the animation begins
  • onUpdate: called every time the animation updates (on every frame while the animation is active).
  • onRepeat: called each time the animation repeats (only available in TweenMax and TimelineMax).
  • onReverseComplete: called when the animation has reached its beginning again when reversed.

To fire a tweenComplete() function when an animation finishes, you'd do:

TweenMax.to("#logo", 1 {x:100, onComplete:tweenComplete});

function tweenComplete() {
  console.log("the tween is complete");
}

Callback Parameters and Scope

Each callback function can optionally be passed any amount of parameters. Since there can be multiple parameters, they must be passed as an Array (even if there is only one).

TweenMax.to("#logo", 1, {x:100, onComplete:tweenComplete, onCompleteParams:["done!"]});

function tweenComplete(message) {
  console.log(message);
}

By default the scope of a callback (what this refers to inside that function) is the tween itself, but you can define it as something else if you prefer, like onCompleteScope: yourScope.

Demo: Basic Callbacks and Parameters

See the Pen Callbacks and parameters by GreenSock (@GreenSock) on CodePen.

For a detailed list of all the special properties, see the TweenMax API docs.

Controlling Animations

To control an animation, you need an instance to work with. The to(), from(), and fromTo() methods all return an instance, so you can store it as a variable and then control it very easily:

//create a reference to the animation
var tween = TweenMax.to("#logo", 1 {x:100});

//pause
tween.pause();

//resume (honors direction - reversed or not)
tween.resume();

//reverse (always goes back towards the beginning)
tween.reverse();

//jump to exactly 0.5 seconds into the tween
tween.seek(0.5);

//jump to exacty 1/4th into the tween's progress:
tween.progress(0.25);

//make the tween go half-speed
tween.timeScale(0.5);

//make the tween go double-speed
tween.timeScale(2);

//immediately kill the tween and make it eligible for garbage collection
tween.kill();

Demo: Basic Control Methods

See the Pen NMrBbE by GreenSock (@GreenSock) on CodePen.

Sequencing with Timelines

Choreographing complex sequences is crazy simple with GSAP's TimelineLite and TimelineMax.

A timeline is a container for tweens where you place them in time (like a schedule). They can overlap or have gaps between them; you have total control. As the timeline's playhead moves, it scrubs across its child tweens and renders them accordingly! Insert as many as you want and control the entire group as a whole with the standard methods (play(), reverse(), pause(), etc.). You can even nest timelines within timelines!

Once you get the hang of timelines, a whole new world of possibilities will open up. They provide a fantastic way to modularize your animation code.

When to Use a Timeline

  • To control a group of animations as a whole
  • To build a sequence without messing with lots of delay values (progressively build so that timing adjustments to earlier animations automatically affect later ones, greatly simplifying experimentation and maintenance)
  • To modularize your animation code
  • To do any kind of complex choreographing
  • To fire callbacks based on a group of animations (like "after all of these animations are done, call myFunction()")

If you're just doing a tween here or there, a timeline is probably overkill.

Basic Sequencing

Timelines have the familiar to(), from(), and fromTo() methods that provide a quick way to create a tween and add() it to the timeline:

//create a timeline instance
var tl = new TimelineMax();
//the following two lines do the SAME thing:
tl.add( TweenMax.to("#id", 2, {x:100}) );
tl.to("#id", 2, {x:100}); //shorter syntax!

By default, animations are inserted one-after-the-other, but it's easy to control precisely where things go using the position parameter.

Demo: Basic Sequencing

See the Pen Timeline: Basic Sequence; by GreenSock (@GreenSock) on CodePen.

We'll focus on TimelineMax's to() method but you can add from() or fromTo() tweens to a timeline in a similar fashion. Also read about staggerTo(), staggerFrom(), staggerFromTo() and others in the TimelineMax API docs.

Method Chaining

Method chaining can keep your code very concise:

var tl = new TimelineMax();
//chain all to() methods together on one line
tl.to(".green", 1, {x:200}).to(".orange", 1, {x:200, scale:0.2}).to(".grey", 1, {x:200, scale:2, y:20});

//we recommend breaking each to() onto its own line for legibility
tl.to(".green", 1, {x:200})
  .to(".orange", 1, {x:200, scale:0.2})
  .to(".grey", 1, {x:200, scale:2, y:20});

Control placement with the Position Parameter

The secret to building gorgeous, precisely-timed sequences is understanding the position parameter. This one super-flexible parameter controls the placement of your tweens, labels, callbacks, pauses, and even nested timelines.

The position parameter follows the vars object as shown below:

tl.to(element, 1, {x:200})
  //1 second after end of timeline (gap)
  .to(element, 1, {y:200}, "+=1")
  //0.5 seconds before end of timeline (overlap)
  .to(element, 1, {rotation:360}, "-=0.5")
  //at exactly 6 seconds from the beginning of the timeline (absolute)
  .to(element, 1, {scale:4}, 6);

The demo below shows the position parameter in action.

See the Pen Timeline: position parameter by GreenSock (@GreenSock) on CodePen.

Timeline Control

Timelines and tweens share a common set of control methods. And since any animation's playhead is controlled by its parent timeline, that means pausing a timeline's playhead automatically affects all of its children! Jump to a different time() or progress() on a timeline and all the children will render accordingly.

See the Pen Timeline Controls by GreenSock (@GreenSock) on CodePen.

Timeline Special Properties

Timelines also have special properties that you can optionally pass into the constructor to configure them. The most commonly used TimelineMax options are:

  • repeat: the number of times the animation will repeat.
  • repeatDelay: the amount of time (in seconds) between repeats.
  • yoyo: if true, playback will alternate forwards and backwards on each repeat.
  • delay: the time (in seconds) before the timeline should start
  • onComplete: a function to call when the timeline has finished playing

Example:

var tl = new TimelineMax({
  repeat:1, 
  yoyo:true, 
  onRepeat:onRepeatHandler,
  onComplete:onCompleteHandler
});

Getter / Setter Methods

Tweens and timelines not only share similar callbacks and control methods, but they also have common methods for getting and setting specific properties of the animation. The most commonly used getter / setter methods are

  • time(): the local position of the playhead (the current time, in seconds) not including any repeats or repeatDelays.
  • progress(): the tween's progress which is a value between 0 and 1 indicating the position of the playhead where 0 is at the beginning, 0.5 is halfway complete, and 1 is at the end.
  • duration(): the animation's duration (in seconds), not including any repeats or repeatDelays.
  • delay(): the animation's initial delay (the length of time in seconds before the animation should begin).

These methods can be used as setters (by passing in a value) or getters (by omitting all arguments). In the code samples below notice that the duration() method can be used in exactly the same way for both the tween and timeline.

var tween = TweenMax.to(".orange", 1, {x:100});
console.log(tween.duration()); //shows 1
tween.duration(2) //sets the duration to 2 seconds

var timeline = new TimelineMax();
timeline.to(".green", 5, {x:200})
  .to(".orange", 5, {x:200, scale:0.2});
//the timeline contains 2 tweens that are both 5 seconds long
console.log(timeline.duration()) //shows 10
timeline.duration(2) //sets the duration to only 2 seconds. For timelines, that actually alters the timeScale to make it play within that duration

Demo: timeScale()

The demo below shows how you can both set and get the timeScale() of a timeline.

See the Pen getter setter method demo by GreenSock (@GreenSock) on CodePen.

Club GreenSock

There are three primary reasons for joining Club GreenSock:

MorphSVGPlugin (Bonus)

One of our most popular and powerful tools, MorphSVG makes it easy to morph one SVG shape into another, regardless of the number of points each has!

See the Pen MorphSVGPlugin Demo by GreenSock (@GreenSock) on CodePen.

Other Bonus Plugins

  • drawSVG - gives you enhanced control over how SVG strokes are revealed.
  • physics2D & physicsProps - for animating objects based on velocity, acceleration, friction, etc.
  • scrambleText - for animated decoding of text.
  • GSDevTools - adds a visual UI for controlling your GSAP animations which can significantly boost your workflow and productivity.
  • throwProps - for animations that flick, toss, and slide gracefully.
  • SplitText - for splitting apart characters, words, or lines of text for easy animation.
  • CustomBounce & CustomWiggle - for creating customized bounce and wiggle eases

Try all bonus plugins for free on Codepen: https://codepen.io/GreenSock/full/OPqpRJ/ Sign up for Club GreenSock today!

Hungry for More?

Now that you've got the basics, it's pretty common to have a new sense of freedom and excitement about your budding animation superpowers. Here are some resources that'll feed your addiction...er...expand your skillset:

Get an all-access pass to premium plugins, offers, and more!

Join the Club

Have you exercised your animation superpowers today? Go make us proud and tell us about it.

- Team GreenSock



User Feedback

Recommended Comments



There are no comments to display.




Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...