问题
I have a cubic bezier with 2 control points. Starting point and control points are known. Need to get all the points of the curve, given the control, starting and ending points. What I wanna to achieve is ..given a value i from 1 to length of curve.. get the X and Y and alpha (angle) of each point in that position. I cannot find a good reference or working code for that. I'm using javascript.
回答1:
If I understand correctly, you are trying to determine the position and slope (tangent to the curve) of the Bezier, at every point.
Let's assume that your start point is (ax, ay), the end point is (dx, dy) and your control points are (bx, by) and (cx, cy).
Position is easy. First, compute the blending functions. These control the "effect" of your control points on the curve.
B0_t = (1-t)^3
B1_t = 3 * t * (1-t)^2
B2_t = 3 * t^2 * (1-t)
B3_t = t^3
Notice how B0_t is 1 when t is 0 (and everything else is zero). Also, B3_t is 1 when t is 1 (and everything else is zero). So the curve starts at (ax, ay), and ends at (dx, dy).
Any intermediate point (px_t, py_t) will be given by the following (vary t from 0 to 1, in small increments inside a loop):
px_t = (B0_t * ax) + (B1_t * bx) + (B2_t * cx) + (B3_t * dx)
py_t = (B0_t * ay) + (B1_t * by) + (B2_t * cy) + (B3_t * dy)
Slope is also easy to do. Using the method given in https://stackoverflow.com/a/4091430/1384030
B0_dt = -3(1-t)^2
B1_dt = 3(1-t)^2 -6t(1-t)
B2_dt = - 3t^2 + 6t(1-t)
B3_dt = 3t^2
So, the rate of change of x and y are:
px_dt = (B0_dt * ax) + (B1_dt * bx) + (B2_dt * cx) + (B3_dt * dx)
py_dt = (B0_dt * ay) + (B1_dt * by) + (B2_dt * cy) + (B3_dt * dy)
And then use Math.atan2(py_dt,px_dt)
to get the angle (in radians).
回答2:
De Casteljau algorithm is more numerically stable. Here it has additional advantage that it calculates the tangent line (and thus, the tangent angle) as the step immediately prior to calculating the point.
But, it works according to a parameter value, not length. It is preferable to calculate points by parameter, not value, as part of rendering the curve. Parameter's range will be [0 ... 1]
, 0
corresponding to the starting, and 1
the ending point of the curve.
回答3:
This library might help, too.
https://code.google.com/p/jsbezier/
来源:https://stackoverflow.com/questions/15397596/find-all-the-points-of-a-cubic-bezier-curve-in-javascript