-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcubic.js
63 lines (44 loc) · 1.34 KB
/
cubic.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
http://jsfiddle.net/rjxh7h0y/1/
// https://github.com/arian/cubic-bezier
var bezier = function(x1, y1, x2, y2, epsilon){
var curveX = function(t){
var v = 1 - t;
return 3 * v * v * t * x1 + 3 * v * t * t * x2 + t * t * t;
};
var curveY = function(t){
var v = 1 - t;
return 3 * v * v * t * y1 + 3 * v * t * t * y2 + t * t * t;
};
var derivativeCurveX = function(t){
var v = 1 - t;
return 3 * (2 * (t - 1) * t + v * v) * x1 + 3 * (- t * t * t + 2 * v * t) * x2;
};
return function(t){
var x = t, t0, t1, t2, x2, d2, i;
// First try a few iterations of Newton's method -- normally very fast.
for (t2 = x, i = 0; i < 8; i++){
x2 = curveX(t2) - x;
if (Math.abs(x2) < epsilon) return curveY(t2);
d2 = derivativeCurveX(t2);
if (Math.abs(d2) < 1e-6) break;
t2 = t2 - x2 / d2;
}
t0 = 0, t1 = 1, t2 = x;
if (t2 < t0) return curveY(t0);
if (t2 > t1) return curveY(t1);
// Fallback to the bisection method for reliability.
while (t0 < t1){
x2 = curveX(t2);
if (Math.abs(x2 - x) < epsilon) return curveY(t2);
if (x > x2) t0 = t2;
else t1 = t2;
t2 = (t1 - t0) * .5 + t0;
}
// Failure
return curveY(t2);
};
};
var duration = 200;
var epsilon = (1000 / 60 / duration) / 4;
var timingFunction = bezier(0.2, 0.9, 0.3, 0.4, epsilon);
console.log( timingFunction(0.01) );