a cubic-bezier solver.
Last active
May 23, 2019 02:30
-
-
Save kamicane/55ad254b84c308882442 to your computer and use it in GitHub Desktop.
[cubic-bezier-solver]
This file contains hidden or 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"; | |
module.exports = function(v1, v2, v3, v4, epsilon){ | |
var curveX = function(t){ | |
var v = 1 - t, | |
b1 = t * t * t, | |
b2 = 3 * t * t * v, | |
b3 = 3 * t * v * v, | |
b4 = v * v * v; | |
return v4.x * b1 + v3.x * b2 + v2.x * b3 + v1.x * b4; | |
}; | |
var curveY = function(t){ | |
var v = 1 - t, | |
b1 = t * t * t, | |
b2 = 3 * t * t * v, | |
b3 = 3 * t * v * v, | |
b4 = v * v * v; | |
return v4.y * b1 + v3.y * b2 + v2.y * b3 + v1.y * b4; | |
}; | |
return function(t){ | |
var x = t, t0, t1, t2, x2; | |
t0 = 0; t1 = 1; t2 = x; | |
if (t2 < t0) return curveY(t0); | |
if (t2 > t1) return curveY(t1); | |
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) * 0.5 + t0; | |
} | |
return curveY(t2); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment