Last active
April 24, 2021 19:43
-
-
Save steveruizok/b6a4f1cf0ffa3a42e3958b6111dee80c to your computer and use it in GitHub Desktop.
Get points on a spine through n points.
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
const pts = [ | |
[300, 100], | |
[500, 200], | |
[700, 250], | |
[800, 300], | |
[900, 500], | |
[800, 600], | |
[650, 650], | |
[500, 600], | |
] | |
// Break out into utils of course, but here's how it can work. | |
function getPoints(pts, steps = 10) { | |
function computePointOnQuadBezCurve(p0, c0, c1, p1, t) { | |
if (t === 0) { | |
return p0 | |
} | |
if (t === 1) { | |
return p1 | |
} | |
const mt = 1 - t, | |
mt2 = mt * mt, | |
t2 = t * t, | |
a = mt2 * mt, | |
b = mt2 * t * 3, | |
c = mt * t2 * 3, | |
d = t * t2 | |
return [ | |
a * p0[0] + b * c0[0] + c * c1[0] + d * p1[0], | |
a * p0[1] + b * c0[1] + c * c1[1] + d * p1[1], | |
] | |
} | |
function getSpline(pts, k = 1) { | |
let p0, | |
[p1, p2, p3] = pts | |
const path = [[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([ | |
[p2[0], p2[1]], | |
[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], | |
]) | |
} | |
return path | |
} | |
const splinePts = getSpline(pts) | |
const finalPts = [] | |
for (let i = 1; i < splinePts.length; i++) { | |
const [p0] = splinePts[i - 1] | |
const [p1, c0, c1] = splinePts[i] | |
for (let k = 0; k <= steps; k++) { | |
const [px, py] = computePointOnQuadBezCurve(p0, c0, c1, p1, k / steps) | |
finalPts.push(px, py) | |
} | |
} | |
return finalPts | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment