Table of Contents
Animating a DOM element
Eases
Delays and Timelines
Overlaps and Labels
Home Web Front-end CSS Tutorial How to Animate on the Web With GreenSock

How to Animate on the Web With GreenSock

Apr 12, 2025 am 09:48 AM

How to Animate on the Web With GreenSock

There are truly thousands of ways to animate on the web. We’ve covered a comparison of different animation technologies here before. Today, we’re going to dive into a step-by-step guide of one of my favorite ways to get it done: using GreenSock.

(They don’t pay me or anything, I just really enjoy using them.)

Why do I prefer GreenSock to other methods? Technically speaking, it’s often the best tool for the job. Its usage is extremely straightforward, even for complex movement. Here are a few more reasons why I prefer using it:

  • You can use them on DOM elements as well as within WebGL/Canvas/Three.js contexts.
  • The easing is very sophisticated. CSS animations are limited to two bezier handles for ease, meaning if you want, say, a bounce effect, you would have to make keyframes up and down and up and down for each pass. GreenSock allows multiple bezier handles to create advanced effects. A bounce is a single line of code. You can see what I mean by checking out their ease visualizer.
  • You can sequence movement on a timeline. CSS animations can get a little spaghetti when you have to coordinate several things at once. GreenSock remains very legible and allows you to control the timeline itself. You can even animate your animations! ?
  • It will perform some calculations under the hood to prevent strange cross-browser behavior as well as things that the spec dictates should be true aren’t — like the way that stacking transforms work.
  • It offers a lot of advanced functionality, in the form of plugins, that you can use if you’d like to take your work a step further — things like Morphing SVG shapes, drawing SVG paths, dragging and dropping, inertia, and more.

People sometimes ask me why I’d use this particular library over all of the other choices. It’s further along than most others — they’ve been around since the Flash was still a thing. This demo reel is pretty inspiring, and also gets the point across that serious web animators do tend to reach for this tool:

What follows is a breakdown of how to create movement on the web, distilled down to the smallest units I could make them. Let’s get started!

Animating a DOM element

Consider a ball that we make with a 

 that’s styled with a border-radius value of 50%. Here’s how we would scale and move it with GreenSock:
<div></div>
Copy after login
gsap.to('.ball', {
  duration: 1,
  x: 200,
  scale: 2
})
Copy after login
Copy after login

In this case, we’re telling GreenSock (gsap) to take the element with the class of.ballmove it.to()a few different properties. We’ve shortened the CSS properties oftransform: translateX(200px)to a streamlinedx: 200(note there’s no need for the units, but you can pass them as a string). We’re also not writingtransform: scale(2). Here’s a reference of the transforms you might want to use with animations, and their corresponding CSS syntax:

x: 100 // transform: translateX(100px)
y: 100 // transform: translateY(100px)
z: 100 // transform: translateZ(100px)
// you do not need the null transform hack or hardware acceleration, it comes baked in with
// force3d:true. If you want to unset this, force3d:false
scale: 2 // transform: scale(2)
scaleX: 2 // transform: scaleX(2)
scaleY: 2 // transform: scaleY(2)
scaleZ: 2 // transform: scaleZ(2)
skew: 15 // transform: skew(15deg)
skewX: 15 // transform: skewX(15deg)
skewY: 15 // transform: skewY(15deg)
rotation: 180 // transform: rotate(180deg)
rotationX: 180 // transform: rotateX(180deg)
rotationY: 180 // transform: rotateY(180deg)
rotationZ: 180 // transform: rotateZ(180deg)
perspective: 1000 // transform: perspective(1000px)
transformOrigin: '50% 50%' // transform-origin: 50% 50%
Copy after login

Duration is what you might think it is: it’s a one-second stretch of time.

So, OK, how would we animate, say, an SVG? Let’s consider the same code above as an SVG:

<svg viewbox="0 0 500 400">
  <circle cx="80" cy="80" r="80"></circle>
</svg>
Copy after login
gsap.to('.ball', {
  duration: 1,
  x: 200,
  scale: 2
})
Copy after login
Copy after login

From an animation perspective, it’s actuallyexactly the same. It’s grabbing the element with the class.ballon it, and translating those properties. Since SVGs are literally DOM elements, we can slap a class on any one of them and animate them just the same way!

Great! We’re cooking with gas.

Eases

I mentioned before that eases are one of my favorite features, let’s take a look at how we’d use them.

Let’s take the original ball. Maybe we want to try one of those more unique bounce eases. It would go like this:

gsap.to('.ball', {
  duration: 1.5,
  x: 200,
  scale: 2,
  ease: 'bounce'
})
Copy after login

That’s it! This version of GreenSock assumes that you want to useease-outtiming (which is better for entrances), so it applies that as a default. All you have to do is specify “bounce” as a string and you’re off to the races.

You might have noticed we also lengthened the duration a bit as well. That’s because the ball has to do more “work” in between the initial and end states. A one-second duration, though lovely for linear or sine easing, is a little too quick for a bounce or an elastic ease.

Delays and Timelines

I mentioned that the defaultease-outtiming function is good for entrances. What about anease-inor ease-in-out exit? Let’s do that as well.

gsap.to('.ball', {
  duration: 1.5,
  x: 200,
  scale: 2,
  ease: 'bounce'
})

gsap.to('.ball', {
  duration: 1.5,
  delay: 1.5,
  x: 0,
  scale: 1,
  ease: 'back.inOut(3)'
})
Copy after login

You might have noticed a few things happening. For example, we didn’t usebounce.inon the second-to-last line (ease: 'back.inOut(3)'). Instead, we used another ease calledbackforease-in-out. We also passed in a configuration option because, as you can see with Greensock’s ease visualizer tool, we’re not limited to just the default configuration for that ease. We can adjust it to our needs. Neat!

You may have also noticed that we chained the animations using a delay. We took the length of the duration of the first animation and made sure the next one has a delay that matches. Now, that works here, but that’s pretty brittle. What if we want to change the length of the first one? Well, now we’ve got to go back through and change the delay that follows. And what if we have another animation after that? And another one after that? Well, we’d have to go back through and calculate all the other delays down the line. That’s a lot of manual work.

We can offload that work to the computer. Some of my more complex animations are hundreds of chained animations! If I finish my work and want to adjust something in the beginning, I don’t want to have to go back through everything. Enter timelines:

gsap
  .timeline()
  .to('.ball', {
    duration: 1.5,
    x: 200,
    scale: 2,
    ease: "bounce"
  })
  .to('.ball', {
    duration: 1.5,
    x: 0,
    scale: 1,
    ease: "back.inOut(3)"
  });
Copy after login

This instantiates a timeline and then chains the two animations off of it.

But we still have a bit of repetition where we keep using the same duration in each animation. Let’s create a default for that as an option passed to the timeline.

gsap
  .timeline({
    defaults: {
      duration: 1.5
    }
  })
  .to('.ball', {
    x: 200,
    scale: 2,
    ease: "bounce"
  })
  .to('.ball', {
    x: 0,
    scale: 1,
    ease: "back.inOut(3)"
  });
Copy after login

That’s pretty cool! Alright, you are probably starting to see how things are built this way. While it might not be a big deal in an animation this simple, defaults and timelines in really complex animations can truly keep code maintainable.

Now, what if we want to mirror this motion in the other direction with the ball, and just… keep it going? In other words, what if we want a loop? That’s when we addrepeat: -1, which can be applied either to a single animation or to the entire timeline.

gsap
  .timeline({
    repeat: -1,
    defaults: {
      duration: 1.5
    }
  })
  .to('.ball', {
    x: 200,
    scale: 2,
    ease: "bounce"
  })
  .to('.ball', {
    x: 0,
    scale: 1,
    ease: "back.inOut(3)"
  })
  .to('.ball', {
    x: -200,
    scale: 2,
    ease: "bounce"
  })
  .to('.ball', {
    x: 0,
    scale: 1,
    ease: "back.inOut(3)"
  });
Copy after login

We could also not only make it repeat but repeat and playback and forth, like a yoyo. That’s why we call this yoyo: true. To make the point clear, we’ll show this with just the first animation. You can see it plays forward, and then it plays in reverse.

gsap
  .timeline({
    repeat: -1,
    yoyo: true,
    defaults: {
      duration: 1.5
    }
  })
  .to('.ball', {
    x: 200,
    scale: 2,
    ease: "bounce"
  })
Copy after login

Overlaps and Labels

It’s great that we can chain animations with ease, but real-life motion doesn’t exactly work this way. If you walk across the room to get a cup of water, you don’t walk. Then stop. Then pick up the water. Then drink it. You’re more likely to do things in one continuous movement. So let’s talk briefly about how to overlap movement and make things fire at once.

If we want to be sure things fire a little before and after each other on a timeline, we can use an incrementer or decrementer. If we take the following example that shows three balls animating one after another, it feels a little stiff.

gsap
  .timeline({
    defaults: {
      duration: 1.5
    }
  })
  .to('.ball', {
    x: 300,
    scale: 2,
    ease: "bounce"
  })
  .to('.ball2', {
    x: 300,
    scale: 2,
    ease: "bounce"
  })
  .to('.ball3', {
    x: 300,
    scale: 2,
    ease: "bounce"
  })
Copy after login

Things get smoother if we overlap the movement just slightly using those decrementers passed as strings:

gsap
  .timeline({
    defaults: {
      duration: 1.5
    }
  })
  .to('.ball', {
    x: 300,
    scale: 2,
    ease: "bounce"
  })
  .to('.ball2', {
    x: 300,
    scale: 2,
    ease: "bounce"
  }, '-=1')
  .to('.ball3', {
    x: 300,
    scale: 2,
    ease: "bounce"
  }, '-=1')
Copy after login

Another way we can do this is to use something called a label. Labels make sure things fire off at a particular point in time in the playhead of the animation. It looks like this:.add('labelName')

gsap
  .timeline({
    defaults: {
      duration: 1.5
    }
  })
  .add('start')
  .to('.ball', {
    x: 300,
    scale: 2,
    ease: "bounce"
  }, 'start')
  .to('.ball2', {
    x: 300,
    scale: 2,
    ease: "bounce"
  }, 'start')
  .to('.ball3', {
    x: 300,
    scale: 2,
    ease: "bounce"
  }, 'start') 
Copy after login

We can even increment and decrement from the label. I actually do this a lot in my animations. It looks like this'start =0.25'.

gsap
  .timeline({
    defaults: {
      duration: 1.5
    }
  })
  .add('start')
  .to('.ball', {
    x: 300,
    scale: 2,
    ease: "bounce"
  }, 'start')
  .to('.ball2', {
    x: 300,
    scale: 2,
    ease: "bounce"
  }, 'start =0.25')
  .to('.ball3', {
    x: 300,
    scale: 2,
    ease: "bounce"
  }, 'start =0.5') 
 
Copy after login

Whew! We’re able to do so much with this! Here’s an example of an animation that puts a lot of these premises together, with a bit of interaction using vanilla JavaScript. Be sure to click on the bell.

If you’re looking more for framework-based animation with GreenSock, here’s anarticle I wrote that covers this in Vue, and atalk I gavethat addresses React — it’s a couple of years old but the base premises still apply.

But there’s still so much we haven’t cover, including staggers, morphing SVG, drawing SVG, throwing things around the screen, moving things along a path, animating text… you name it! I’d suggest heading over toGreenSock’s documentationfor those details. I also have acourse on Frontend Mastersthat covers all of these in much more depth and the materials areopen source on my GitHub. I also have a lot ofPens that are open sourcefor you to fork and play with.

I hope this gets you started working with animation on the web! I can’t wait to see what you make!

The above is the detailed content of How to Animate on the Web With GreenSock. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It&#039;s out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That&#039;s like this.

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Using Markdown and Localization in the WordPress Block Editor Using Markdown and Localization in the WordPress Block Editor Apr 02, 2025 am 04:27 AM

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...

How to select a child element with the first class name item through CSS? How to select a child element with the first class name item through CSS? Apr 05, 2025 pm 11:24 PM

When the number of elements is not fixed, how to select the first child element of the specified class name through CSS. When processing HTML structure, you often encounter different elements...

See all articles