Created
September 18, 2015 11:35
-
-
Save ktcy/38cc1adb74239d2005f3 to your computer and use it in GitHub Desktop.
CSS `cubic-bezier()` timing function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
export default function cubicBezier(x1, y1, x2, y2) { | |
let ax, bx, cx, ay, by, cy; | |
ax = 3 * (x1 - x2) + 1; | |
bx = 3 * x2 - 6 * x1; | |
cx = 3 * x1; | |
ay = 3 * (y1 - y2) + 1; | |
by = 3 * y2 - 6 * y1; | |
cy = 3 * y1; | |
return function(x, accuracy) { | |
let t, i, sample, derivative, low, high; | |
if (x <= 0) { | |
return 0; | |
} else if (x >= 1) { | |
return 1; | |
} | |
t = x, i = 8; | |
while (i--) { | |
sample = ((ax * t + bx) * t + cx) * t - x; | |
if (-accuracy < sample && sample < accuracy) { | |
return ((ay * t + by) * t + cy) * t; | |
} | |
derivative = (3 * ax * t + 2 * bx) * t + cx; | |
if (-0.000001 < derivative && derivative < 0.000001) { | |
break; | |
} | |
t = t - sample / derivative; | |
} | |
t = x, low = 0, high = 1; | |
while (low < high) { | |
sample = ((ax * t + bx) * t + cx) * t - x; | |
if (-accuracy < sample && sample < accuracy) { | |
break; | |
} | |
sample < 0 ? (low = t) : (high = t); | |
t = 0.5 * (high + low); | |
} | |
return ((ay * t + by) * t + cy) * t; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment