Delving into Greensock with a Moody Creature

This is my first trial run using the GSAP (Greensock Animation API) library for animation of SVG (Scalar Vector Graphics). SVG’s are super-sharp images with underlying code that is structured a lot like HTML. When you “inline” an SVG, or include the SVG code directly in the HTML of a webpage, you can use CSS and Javascript to animate its parts.

The animations below are made possible with vanilla Javascript as well as two lines of code that use GSAP. Click on the buttons (the default is set to “happy”) and you should be able to see the critter change expressions.

Why GSAP? I have found that using Vanilla JS and CSS is great if you want to do basic animations, but if you need something that smoothly transitions a complex shape from one state to another, you really need an animation library.

The GSAP library is terrific for this, and there is a free version and a paid version. My demo below uses the free version and at this point animates the mouth. I plan on animating other feature like the eyes on an upcoming demo.

I plan to include a breakdown of how I wrote the code in an upcoming post, but for those of you who are curious, I have the code below with comments.

  • The CSS is minimal and really just centers the criter and controls while styling the buttons.

  • The HTML will show you how I set up the SVG and the controls. Note the data attributes, which determine the mouth shape that each button triggers.

  • The JS will show you how I used Vanilla JS to create an object full of mouth SVG paths and set up the click listeners. You will also see how I used only two lines of code calling the GSAP logic to tween the animations.

Enjoy!




#critter-container svg {
    display: block;
    margin: 0px auto;
    
}
#controls {
  	display: flex;
  	justify-content: center;	
    flex-wrap: wrap;
}
button {
  	background-color: #116fca;
  	color: white;
  	padding: 8px 5px;
  	border-width: 0px;
  	border-radius: 2px;
  	min-width: 80px;
  	cursor: pointer;
  	margin: 10px 3px 2px 3px;
}