Search code examples
javascriptalgorithmcurvebeziercubic-spline

Algorithm for finding control points of cubic bezier (implementation details)


I've googled a lot, but all algorithms I found used equations for finding control points. I've thought there is simpler solution to do it and found some implementation in ExtJS source code: http://docs-devel.sencha.com/extjs/4.1.2/source/Draw.html#Ext-draw-Draw-method-getAnchors. It uses angles betweeen nearest points of line to detect control points and some hacks.

Can somebody define what kind of algorithm for searching control points is this? I am stuck in manipultation with PI and angles. May be there is more detailed and cleaner explanation, or common idea for this way of solving the problem?


Solution

  • It's Catmull-Rom fitting: the code tries to find an appropriate tangent through point X, based on the location of points X-1 and X+1, such that the tangent is parallel to the line (X-1)--(X+1), and then fiddles with the control points that yields, to make sure the "incoming" and "outgoing" tangents yield an aesthetically pleasing curve.

    enter image description here

    1. have points
    2. assume tangent equal to (p-1)--(p+1)
    3. that generally looks horrible
    4. scale control points a little for better fit

    How you do step 4 is technically no longer Catmull-Rom, because genuine Catmull-Rom splines stop once the tangent's been set up. The usual approach if you do need a step 4 is to scale the points in based on projected distance: if you project point X on the line (X-1)--(X+1), it'll rarely ever be exactly in the middle of the line, but at some distance v% from point X-1 and distance (100-v)% from point X+1, so you scale the found tangent accordingly.