Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all the points of a cubic bezier curve in javascript [closed]

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.

like image 839
Claudio Ferraro Avatar asked Mar 13 '13 22:03

Claudio Ferraro


1 Answers

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).

like image 135
Rahul Banerjee Avatar answered Sep 30 '22 00:09

Rahul Banerjee