Search code examples
javascripttweeneasinggsap

Calculate GSAP eased tween duration given desired starting velocity


I have a sequence of two GSAP tweens. The second tween is dependent on the first. The first tween moves an element to the right using Power3.easeIn. When this first tween ends, I calculate the instantaneous velocity of the element so I know how fast it was moving right at the end of the tween.

The second tween then needs to move a child of this element to the right using Power2.easeOut. This tween should start at the same velocity that the previous tween ended with. The distance that the child moves during this tween is fixed. How can I calculate the duration of the second tween such that it starts with the desired velocity?

EDIT: Here is a jsbin demonstrating what I'm attempting to do.


Solution

  • If I understand your question properly, this is EXACTLY what GSAP's ThrowPropsPlugin is for. Not only can it track the moment-by-moment velocity of any property of any object, but it can then create a tween that begins with that precise velocity and then glides to a stop naturally and you can even tell it where it should stop (or provide a range or snapping points...lots of options).

    The ThrowPropsPlugin.to() method does the magic of figuring out the duration for you. All you do is feed in the target and end value (or range or snapping points).

    The docs are at http://greensock.com/docs/#/HTML5/GSAP/Plugins/ThrowPropsPlugin/ where you'll find several examples too.

    Here's a codepen demo based on your example: https://codepen.io/anon/pen/wGGdmq

    ThrowPropsPlugin.to(child, {x:{velocity:ThrowPropsPlugin.getVelocity(parentElement, "x"), end:250}, ease:Power2.easeOut});
    

    Notice you can change the duration of the first tween as well as the x position and the child will still animate properly. (That's what you were looking for, right?)

    Disclaimer: ThrowPropsPlugin is a membership benefit of Club GreenSock so it is not in the public GSAP downloads.