Lomiri
Loading...
Searching...
No Matches
KeySpline.js
1/** MIT License
2 *
3 * KeySpline - use bezier curve for transition easing function
4 * Copyright (c) 2012 Gaetan Renaudeau <renaudeau.gaetan@gmail.com>
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 */
24/**
25* KeySpline - use bezier curve for transition easing function
26* is inspired from Firefox's nsSMILKeySpline.cpp
27* Usage:
28* var spline = new KeySpline(0.25, 0.1, 0.25, 1.0)
29* spline.get(x) => returns the easing value | x must be in [0, 1] range
30*/
31
32.pragma library
33
34function keySpline (mX1, mY1, mX2, mY2) {
35
36 this.get = function(aX) {
37 if (mX1 == mY1 && mX2 == mY2) return aX; // linear
38 return CalcBezier(GetTForX(aX), mY1, mY2);
39 }
40
41 function A(aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1; }
42 function B(aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1; }
43 function C(aA1) { return 3.0 * aA1; }
44
45 // Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.
46 function CalcBezier(aT, aA1, aA2) {
47 return ((A(aA1, aA2)*aT + B(aA1, aA2))*aT + C(aA1))*aT;
48 }
49
50 // Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2.
51 function GetSlope(aT, aA1, aA2) {
52 return 3.0 * A(aA1, aA2)*aT*aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
53 }
54
55 function GetTForX(aX) {
56 // Newton raphson iteration
57 var aGuessT = aX;
58 for (var i = 0; i < 4; ++i) {
59 var currentSlope = GetSlope(aGuessT, mX1, mX2);
60 if (currentSlope == 0.0) return aGuessT;
61 var currentX = CalcBezier(aGuessT, mX1, mX2) - aX;
62 aGuessT -= currentX / currentSlope;
63 }
64 return aGuessT;
65 }
66}