javascriptsvgbezierapproximation

SVG: Convert Arcs to Cubic Bezier


I'm trying to do something that i though would be pretty simple: Replacing all Arcs in an SVG path with Cubic Bezier Curves.

This: http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes doesn't really help me as it doesn't really say anything about conversion.

I know how to make simple Arcs, but the SVG Arcs do have a lot of parameters.

So what i need is basically just an algorithm that takes:

rx ry x-axis-rotation large-arc-flag sweep-flag x y

(and also the start point of the arc)

and calculates:

x1 y1 x2 y2 x y

(of course, the start point, x and y keep the same values...)

Does anybody know something like this?

Thanks in advance! :-)


Solution

  • Turns out this is impossible. I mean, mathematically, at least. You can't do circular arcs with plain cubic Bezier curves, you're always going to have an error, so depending on the arc's angle, you're going to probably need more than one Bezier curve.

    With that said, cubic Bezier curves work quite well for quarter-circle arcs, so if you have arcs smaller than that, you can use a single curve, and if you have wider arcs, you can simply divide it by a sensible number (between quarter and half circle? Use two curves. Between half and three quarts? Use three. Full circle? Four curves. Pretty simple).

    So, how much work is this? Turns out, if you have to do it from scratch: a fair bit of work, but you can just jump to the "okay so what is the final formula I need" and then it becomes relatively simple.

    If we have angle phi, then the cubic curve approximation of your arc, provided we align the start of our arc with the x-axis (so that the arc starts at y=0, and runs counter clockwise from there), and we have an arc radius R, is:

    start coordinate = {
      x: R,
      y: 0
    }
    
    control point 1 = {
      x: R,
      y: R * 4/3 * tan( phi / 4)
    }
    
    control point 2 = {
      x: R * ( cos(phi) + 4/3 * tan( phi/4 ) * sin(phi) ),
      y: R * ( sin(phi) - 4/3 * tan( phi/4 ) * cos(phi) ),
    }
    
    end coordinate = {
      x: R * cos(phi),
      y: R * sin(phi)
    }
    

    Maths! But really just "plug in angle, get the coordinates we need". Simple!

    But what if our arc is not aligned to the x-axis? We apply a dumb "rotate + translate" to put align our arc, and then we run the rotation/translation in reverse when we're done. Explained here.