Skip to content

Instantly share code, notes, and snippets.

@steveruizok
Last active May 13, 2022 06:29
Show Gist options
  • Save steveruizok/b9035a3406f04a6a78326755a54ad020 to your computer and use it in GitHub Desktop.
Save steveruizok/b9035a3406f04a6a78326755a54ad020 to your computer and use it in GitHub Desktop.
Get a Bezier curve to fit the provided points.
/*
Use this with canvas.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, px, py).
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/bezierCurveTo
Uses a Catmull-Rom spline (https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline).
*/
/**
* Get a bezier curve data to for a spline that fits an array of points.
* @param points An array of points formatted as [x, y]
* @param k
* @returns An array of points as [cp1x, cp1y, cp2x, cp2y, px, py].
*/
export function getSpline(pts: number[][], k = 1) {
let p0: number[],
[p1, p2, p3] = pts
const path: number[][] = [p1]
for (let i = 1, len = pts.length; i < len - 1; i++) {
p0 = p1
p1 = p2
p2 = p3
p3 = pts[i + 2] ? pts[i + 2] : p2
path.push([
p1[0] + ((p2[0] - p0[0]) / 6) * k,
p1[1] + ((p2[1] - p0[1]) / 6) * k,
p2[0] - ((p3[0] - p1[0]) / 6) * k,
p2[1] - ((p3[1] - p1[1]) / 6) * k,
p2[0],
p2[1],
])
}
return path
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment