Toggle animation using gsap: Stick figure

I posted this on twitter and created this for a CodePen challenge. Inspired by dribble shot.

I am writing this blog as an overview of how I created this pen. This is not a detail blog, just an overview and important bits. Please keep open the code and preview while reading this blog.

CodePen Demo:

See the Pen theme-toggle: stick-figure by trapti (@tripti1410) on CodePen.

SVG creation

I created an SVG of rectangular shape viewBox of 150x200. All the body parts are individual elements, mostly they are basic shapes. I only created the initial state in the illustrator and exported that as SVG from the four states(this is shown in the below image).

Stick figure

Stick figure animation

As you can see in the above image, there are 4 states. I used gsap to animate the stick figure for all the states.

Important: animated SVG elements attribute using e.g. gsap.to(”.class”,{ attr: {x1: , x2: , y1: ,y2:}})

Leg animation: All the leg parts are simple line elements. So all the elements have these four attributes x1, x2, y1, y2. By modifying these attributes, I animated legs. It may seem like complex numbering, but it’s simply math and logic. When the leg is vertical, x1 = x2 but y1y2. Difference of y values will be the length of the line and vice versa. The four values for inclined legs will vary and depend on the line angle.

Eyes: I did Blinking eyes using scaleY 0 and 1.

Entire stick figure is inside a group element. And using this group element stick figure is movable for toggling inside button.

Face: I moved face up and down using cy attribute.

Highlights: There are 4 lines which are path elements. I did animating path elements using drawSVG.

Rest of the things are easy to understand. I attached all the animations to one gsap timeline named wakeup_tl, and it is in the paused state.

Putting it in the action with the toggle button

There were a few things I did on toggle on and off.

Toggle On: Play the wakeup_tl and highlight_tl timeline. Once the animation completes, it will call a handler that activates all the actions for light mode.

Toggle Off: Reverse the wakeup_tl timeline. Each click should show the little highlight, so restart highlight_tl. Once the animation completes, it will call a handler that activates all the actions for dark mode.

Thanks for reading, if you like my content then consider sharing it on Linkedin and Twitter and do tag me. Stay connected.
BACK HOME