Reputation: 875
jQuery has an easing function called swing that is used when animating the movement of an object. I'm trying to mentally parse the source but am not adept at reading this code. I'm asking for someone to write the algorithm in pseudocode or C, or even javascript without all of the OO prototype stuff.
Here is the documentation where the easing function is mentioned: http://api.jquery.com/animate/
Here is the source code:
File 1) https://github.com/jquery/jquery/blob/master/src/effects.js
File 2) https://github.com/jquery/jquery/blob/master/src/effects/Tween.js
It looks like it's implemented in file two on line 107. It's confusing because the function has one argument, p, which I'm guessing is for percent. Then it appears as if the function is called on line 35 with five arguments:
percent, this.options.duration * percent, 0, 1, this.options.duration
I would think the easing function would definitely need the duration incorporated into the algorithm. So what's going on here?
Thanks
Upvotes: 0
Views: 140
Reputation: 2869
It determines how far along the value of the property should be, based on the percentage completion of the animation. swing
starts and ends slow, linear
is a constant velocity.
Suppose you want to change the height of an element from 100px to 200px, over 1 second. We could just change the height from 100 to 200 and then wait one second, but that would look really terrible. What we actually want is a way to cut up the duration into a bunch of chunks, and then a way to determine what the height should be at any given point in time.
To solve the first issue (chunking time), we'll just define an arbitrary rate, like maybe 50 chunks per second. To solve the second issue (what's the height after one chunk of time?) we'll define a mathematical function: currentHeight = (timeSinceStart / duration) * 100 + 100
Now we can start counting through chunks, running the numbers, and changing our height smoothly. 102px, 104px, 106px, 108px... This is linear easing because the value changes linearly as time increases, and it looks pretty good!
We can make it better, though. Real objects have weight and inertia which makes them harder to start and stop, but easier to keep moving. They don't start moving at full speed and we have to slow them down to make them stop. One way to simulate this is to tweak the easing/timing function using the almighty power of trigonometry to get something like this: currentHeight = (0.5 - cos((timeSinceStart / duration) * pi) / 2) * 100 + 100
jQuery calls this swing easing because the value seems to swing like a pendulum. The native CSS transition timing function is simply called ease-in-out
. The fun part is when you start carefully choreographing your animations and writing custom timing functions to imply a specific weight or friction to your interface elements. Big things tend to be heavy, tiny things have very little inertia, dangerous switches are intentionally hard to flip.
Upvotes: 1