Skip to content

Instantly share code, notes, and snippets.

@kamicane
Last active May 23, 2019 02:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamicane/55ad254b84c308882442 to your computer and use it in GitHub Desktop.
Save kamicane/55ad254b84c308882442 to your computer and use it in GitHub Desktop.
[cubic-bezier-solver]

a cubic-bezier solver.

"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