How to find out Y coordinate of specific point in bezier curve in canvas?

Jan Kožušník picture Jan Kožušník · Jan 5, 2013 · Viewed 8.1k times · Source

I need to find out Y coordinate of specific point of bezier curve in canvas. Do you know, how to find it out? Thank you

Answer

DerekR picture DerekR · Jan 7, 2013

Using de Casteljau's algorithm you can find the coordinates x and y of a bezier curve for any t, the percentage or interpolation step. So a t of .1 would give you the x and y at 10% of the curve from the beginning. A t of .9 would be 90% from the beginning, and so on.

In our cubic bezier we have p0 (point 0), cp0 (control point 0), cp1 (control point 1), and p1 (point 1).

In the first step of the algorithm we draw a line connecting p0 and cp0, another line connecting cp0 and cp1, and another still connecting cp1 and p1. Then for all 3 of these lines we're going to find the point on them that is t % from the start of them.

I'll call the points as follows:

  • p0 -> cp0 = A
  • cp0 -> cp1 = B
  • cp1 -> p1 = C

    Ax = ( (1 - t) * p0x ) + (t * cp0x);
    Ay = ( (1 - t) * p0y ) + (t * cp0y);
    Bx = ( (1 - t) * cp0x ) + (t * cp1x);
    By = ( (1 - t) * cp0y ) + (t * cp1y);
    Cx = ( (1 - t) * cp1x ) + (t * p1x);
    Cy = ( (1 - t) * cp1y ) + (t * p1y);
    

The second step is very much like the first. In the first we connected the four points with lines and then found 3 new points on them. In this step we'll connect those 3 points with lines find 2 new points on them. I'll call these two new points D and E.

    Dx = ( (1 - t) * Ax ) + (t * Bx);
    Dy = ( (1 - t) * Ay ) + (t * By);

    Ex = ( (1 - t) * Bx ) + (t * Cx);
    Ey = ( (1 - t) * By ) + (t * Cy);

Finally, we can connect these last two points with another line, and find the last point on it which will give us the point on the bezier curve for that t. I'll call this point P.

    Px = ( (1 - t) * Dx ) + (t * Ex);
    Py = ( (1 - t) * Dy ) + (t * Ey);

There we go, we now have the x and y coordinate of a point on the bezier that is t% from the start. I'll add some pictures soon.

enter image description here