Search code examples
svggraphicstrigonometrybezierspline

How to approximate a half-cosine curve with bezier paths in SVG?


Suppose I want to approximate a half-cosine curve in SVG using bezier paths. The half cosine should look like this:

half cosine

and runs from [x0,y0] (the left-hand control point) to [x1,y1] (the right-hand one).

How can I find an acceptable set of coefficients for a good approximation of this function?

Bonus question: how is it possible to generalize the formula for, for example, a quarter of cosine?

Please note that I don't want to approximate the cosine with a series of interconnected segments, I'd like to calculate a good approximation using a Bezier curve.

I tried the solution in comments, but, with those coefficients, the curve seems to end after the second point.


Solution

  • After few tries/errors, I found that the correct ratio is K=0.37.

    "M" + x1 + "," + y1
    + "C" + (x1 + K * (x2 - x1)) + "," + y1 + ","
    + (x2 - K * (x2 - x1)) + "," + y2 + ","
    + x2 + "," + y2
    

    Look at this samples to see how Bezier matches with cosine: http://jsfiddle.net/6165Lxu6/

    The green line is the real cosine, the black one is the Bezier. Scroll down to see 5 samples. Points are random at each refresh.

    For the generalization, I suggest to use clipping.