Created
September 7, 2022 11:19
-
-
Save mrchaofan/fedb5554af1ed20b32879215c729e382 to your computer and use it in GitHub Desktop.
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
function calcBezier(t: number, p1: number, p2: number): number { | |
return (((1 + 3 * p1 - 3 * p2) * t + (-6 * p1 + 3 * p2)) * t + 3 * p1) * t; | |
} | |
const PRECISION = 0.0000001; | |
const MAX_ITERATIONS = 12; | |
function binarySubdivide( | |
x: number, | |
a: number, | |
b: number, | |
x1: number, | |
x2: number | |
): number { | |
let currentX, | |
currentT, | |
i = 0; | |
do { | |
currentT = a + (b - a) / 2; | |
currentX = calcBezier(currentT, x1, x2) - x; | |
if (currentX > 0) { | |
b = currentT; | |
} else { | |
a = currentT; | |
} | |
} while (Math.abs(currentX) > PRECISION && ++i < MAX_ITERATIONS); | |
return currentT; | |
} | |
export function cubicBezier(x1: number, y1: number, x2: number, y2: number) { | |
return (x: number): number => { | |
return x === 0 || x === 1 | |
? x | |
: calcBezier(binarySubdivide(x, 0, 1, x1, x2), y1, y2); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment