Skip to content

Instantly share code, notes, and snippets.

@justvanrossum
Created May 30, 2022 15:23
Show Gist options
  • Save justvanrossum/6efeb82817710bbef71ba5e15abe3275 to your computer and use it in GitHub Desktop.
Save justvanrossum/6efeb82817710bbef71ba5e15abe3275 to your computer and use it in GitHub Desktop.
Cubic Bezier: find Y given X
# https://twitter.com/mttymtt/status/1531022994323251202
# DrawBot visualization
# FontTools for helper code
from fontTools.misc.bezierTools import calcCubicParameters, solveCubic
scaleFactor = 500
pt0 = (0, 0)
pt1 = (0.37, 0.05)
pt2 = (0.65, 0.9)
pt3 = (1, 1)
(ax, ay), (bx, by), (cx, cy), (dx, dy) = calcCubicParameters(pt0, pt1, pt2, pt3)
bez = BezierPath()
bez.moveTo(pt0)
bez.curveTo(pt1, pt2, pt3)
translate(100, 100)
fill(None)
stroke(0)
strokeWidth(4 / scaleFactor)
scale(scaleFactor)
drawPath(bez)
stroke(1, 0, 0)
strokeWidth(1 / scaleFactor)
steps = 10
for i in range(steps + 1):
x = i / steps
line((x, 0), (x, 1))
ts = solveCubic(ax, bx, cx, dx - x)
ts = [t for t in ts if 0 <= t <= 1]
t = ts[0]
y = ay * t**3 + by * t**2 + cy*t + dy
line((0, y), (1, y))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment