I'd like some function to compute the duration for an animation such that even when the distance changes, the speed remains constant.
====================================
| |
|<============ width =============>|
| |
| <====== distance1 ======>|
| |
| <=== distance2 ===>|
| |
===================================
This is trivial to accomplish when dealing with linear easing,
function getDuration (width, distance, duration) {
return duration * (1 - distance / width);
}
However, this becomes much more complex when using non-linear easing functions, such as easeInOutQuad
(An illustration of this problem: http://jsfiddle.net/Wexcode/rdrbm8et/3/).
Given an easing function, such as easeInOutQuad
, how do I compute the duration such that the speed for any distance remains constant?
easeInOutQuad: function (t) { return t<.5 ? 2*t*t : -1+(4-2*t)*t },
Source: https://gist.github.com/gre/1650294
Source: http://api.jqueryui.com/easings/
Given a function y = f(t)
, where y is the distance and t is the time simply solve for t, and use the t = g(y)
function to determine how long it takes to get to a given distance.
For instance, in the easeInOutQuad
easing, -1+(4-2*t)*t
can be solved:
Source: http://www.wolframalpha.com/input/?i=Solve%28y+%3D+-1%2B%284-2*t%29*t%2C+t%29
In practice, you would multiply t
times your duration
to get your new duration.
var ratio = distance / width;
if (ratio <= .5) {
return duration * Math.sqrt(ratio * 1/2);
} else if (ratio <= 1) {
return duration * (1 - Math.sqrt(1-ratio) / Math.sqrt(2));
}
http://jsfiddle.net/Wexcode/rdrbm8et/6/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With