Chapter 8. Animating with GreenSock

In the previous chapter, we went over some of the reasons you might choose GreenSock as an animation library. In this chapter, we’ll cover the basics of how to animate.

Even if you’re more comfortable with CSS, you can still master GreenSock. You don’t necessarily need to know everything about JavaScript to use it for animation. Certainly people who are comfortable with JavaScript will pick it up a little faster and be able to debug with a little more ease, but I do think the syntax is simple and straightforward enough that a CSS developer will be able to get to grips with it. Heck! It’s even easier than CSS in some ways: CSS separates concerns by putting the keyframes in one area and applying them on the properties separately, while GreenSock allows you to manipulate everything in one spot.

GreenSock has been under development for 10 years: it was previously a Flash tool. This gives it an enormous leg up on the competition, as the designers are intimately familiar with the issues users run into. They are also very approachable, and there are some regulars around to help on the forums, so if you get stuck there’s a pretty good community around to help you get back on your feet.

Let’s get started!

Basic GreenSock Syntax

We’ll start with a really simple example, the result of which is shown in Figure 8-1:

TweenMax.to(".element", 2, { x: 100 });
Figure 8-1. If we have a ball with a class of .element, here’s what we’ll see

In this example, the ball moves to the right by 100 px. Let’s break down some of this syntax bit by bit, and consider a few extra options.

TweenMax/TweenLite

TweenMax.to(".element", 2, { x: 100 });

The TweenMax   at the start of the statement tells the browser we’re going to use the GreenSock Animation API code that was loaded from the library we imported. This can be interchanged with TweenLite, if you choose to use the smaller version of the library. The advantage of TweenLite is that it’s very small, while the advantage of TweenMax is that it comes equipped with things like loops, CSS properties (which you will find you might need), and the TimelineMax library, which extends the smaller TimelineLite (we’ll dig into the timeline in the next chapter). The two are interchangeable and don’t change the way the animation works, aside from one having broader offerings.

.to/.from/.fromTo

TweenMax.to(".element", 2, { x: 100 });

The next piece is the .to method, which, as you might expect, tells the element to change to a different state.

You can also use .from, which means the element originates from whatever you specify in the curly braces (the animation object) and changes to its default values, or .fromTo, which gives you more granular control over where something starts and where it ends.

.fromTo becomes very useful for animations that will be retriggered, because you can be more certain of the starting and ending points. For example, say you fire an animation and it scales up by 50%. Then you ask it again to scale up by 50%—but it’s already there. That animation will look like it does nothing on the secondary trigger.

When we use .fromTo, the syntax looks a little bit different:

TweenMax.fromTo(".element", 2, {
  x: 0
 }, {
  x: 100
 });

You can see I also broke things out over a few more lines so it’s a little more legible. Now we can see fairly clearly that the element will go from the 0 coordinate on the x-axis to 100.

Staggering

We can also use .staggerTo, .staggerFrom, or .staggerFromTo. These will take the same animation and repeat it in a kind of cascade, applied to a group of objects that you designate. With SVG I find it helpful to place the items in a group together and add a class to the group to achieve this.  For example, in this code, the animation will be applied to all circles inside the group with the class .element:

TweenMax.staggerTo(".element circle", 2, {
  x: 100
}, 0.1);

This code  snippet shows what we’ve changed: we’re using .staggerTo instead of .to and have added an extra parameter at the end of the statement: 0.1. This controls the time between each of the staggers. We’re also now targeting all of the circles in a group with a class of .element. The output will look something like Figure 8-2.

Figure 8-2. The balls are all animating with the same values, but staggered in timing, one after another

Reverse-Order Staggers

If you’d like the stagger to start from the last element and go to the first, it’s very easy to do. Simply use a negative value for the interval (shown here as the -0.1 value):

TweenMax.staggerTo(".element 
   circle", 2, {
  x: 100
}, -0.1);

There are more advanced types of staggers available, including using the cycle property and randomized staggering values. For more information about these, check out Chapter 11.

Elements

TweenMax.to(".element", 2, { x: 100 });

The way  that GreenSock targets elements is similar to querySelector() or querySelectorAll() in native JavaScript and even closer to the behavior of a jQuery selector, in that you can pass in one or multiple elements, and they can be classes, IDs, or attributes like path, circle, or rect. You don’t have to worry about nodelists; all of that is abstracted away for you, which makes working with the DOM and cross-browser support much simpler.

You can use a quoted selector string, like in this example, to target elements directly, but GreenSock will happily accept variables too, if that’s your jam (for example, var el = document.querySelector(".el");). I tend to use variables like this when I am targeting an element multiple times, to avoid repetition and multiple lookups.

Duration

TweenMax.to(.element", 2, { x: 100, delay:
   2 });

This is probably the simplest of the values we’ll cover. We’re going to pass in an integer, and it affects how long the animation will run. 2 is 2 seconds; 0.3 would be 0.3 seconds, or 300 milliseconds. Just like with the .element value, we can pass in a variable here too. I tend to only do that if there are multiple elements and animations that I want firing for the same exact duration, though, and that situation is fairly rare.

Delay

TweenMax.to(.element", 2, { x: 100, delay:
   2 });

If you would like to make your animation wait for a bit before firing, you can use delay. Delay is useful for chaining, or setting things a bit before or after one another, but in the next chapter we will cover a much more efficient and organized way to chain effects with the timeline tool.

Properties to Animate

We talked briefly  about how our example code will move the ball to the right by 100 px, but let’s dig into that a little more. What does that x stand for? It actually stands for transform: translateX(100px). (It should not be confused with the x attribute in elements like rects in SVG.) Remember when I mentioned that transforms and opacity are the most performant things to animate? Well, GreenSock’s developers know this, so they nicely created some shorthand for us—we can use x, y, z, scale, and rotation (instead of rotate in CSS). Handily, because they’ve broken out the properties, we can use them individually and at different times. That saves us a lot of typing and makes our code much easier to read.

Keep in mind that if you’re transforming within the SVG DOM, it will use the coordinate system within the viewBox, so you won’t actually be using true pixels. You might recall from previous chapters that this is actually a really great feature, because it means we can easily scale and create complex responsive animations (more on this in Chapter 16).

Animating Transforms in CSS Equivalent

Because transform is one property in CSS, it’s a hassle to apply different transforms at different times to one element. They end up having a stacking order and are applied one by one, unless you write out each value at the interpolated percentage for each change.

I’ve written more about this in an article for CSS-Tricks.

GreenSock gives us a huge life upgrade by breaking these properties apart so we can have finer control of movement.

The CSS Working Group is planning to break transforms out into their own properties, but at the time of publishing the timeline for implementation and extent of browser support were unclear. Chrome has some experimental implementations.

We also have opacity, which works like it does in CSS: we can supply values from 0 to 1, with 0 being completely transparent and 1 being completely opaque. Additionally, GreenSock offers a custom value called autoAlpha, which also takes values from 0 to 1. This value couples opacity and visibility: hidden, so it removes the element from/adds it into the DOM completely. 

This is important because an element with opacity: 0 is still able to react to mouse/touch/keyboard events and is included in the accessibility tree used by screen readers. An element with visibility: hidden is not. autoAlpha ensures that when the element has fully faded out, it is correctly hidden from interaction as well as from view.

You can also animate any number of other CSS values. Color, width, height, perspective—they’re all fair game. There are a few things to keep in mind, though. First, any property with a dash in its name becomes camelCased. For example, background-color would be backgroundColor, and border-radius would be borderRadius. Also, any value that isn’t a number has to be passed in as a string, surrounded in quotes. So, a color value would be color: "#333333".

When animating two properties, we separate them by commas (we treat the properties that we’re animating like objects):

TweenMax.to(.element", 2, {
 x: 100, 
 y: 50 
});

Easing

Easing is optional, so I didn’t include it in the first example. But easing is perhaps the most powerful tool in GreenSock: it brings pieces of static code to life. We can add easing as follows:

TweenMax.to(.element", 2, {
 x: 100, 
 y: 50,
 ease: Sine.easeOut 
});

When we write this, ease: always stays consistent. Here, Sine is the type of ease. Most of the easing curve types have three options: .easeIn, .easeOut, and .easeInOut. They affect which direction the Bézier shape of the ease flows in. There are many different types of GreenSock eases. When I was first learning, I found the GreenSock Ease Visualizer to be an invaluable tool in visualizing and exploring all of the different options (see Figure 8-3).

Figure 8-3. The GreenSock Ease Visualizer: an invaluable interactive tool

Recently, GreenSock introduced a new type of ease called Custom. You need to load the CustomEase plug-in in order to use it, but it enables you to pass in SVG paths, and you can play with the Ease Visualizer to manipulate the paths (which is especially nice because you can watch the demo move). This is an incredible feature, as sometimes the type of easing you use makes all the difference between awkwardness and realistic, impressive movement.

Hot Easing Tip

Despite what their names might suggest, .easeOut is actually really good for entrances. .easeIn is great for exits, and I tend to use .easeInOut sparingly, often for intermediary states.

In and out in easing refer to the beginning and end of the animation, and you want the “easy” (slower) part of the animation to be the part that’s closer to the resting state of the object (the end for entrances, the beginning for exits), with faster motion as it moves offscreen.

This might seem like a lot to dig into and understand, but once you’ve worked with the syntax a few times, it’s relatively easy to commit it to memory because you’ll use the same general pattern again and again. I highly suggest typing out some of the code in this chapter to keep it fresh in your mind.

In future chapters, we’ll dig into some really advanced and fun things, now that you have the basics down!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.196.175