SVG: Convert Arcs to Cubic Bezier
Most SVG rendering libraries have to do this because 2D graphics libraries don't seem to directly support arcs that are rotated with respect to the X axis.
So you could look up the code in, say, Batik. Or look at the arcTo()
method in my SVG library (which also borrows from Batik):
AndroidSVG / SVGAndroidRenderer.java / line 2889
It's Java, but should be easily converted to JS.
You can also look at this function from SnapSVG which might have been used somehow by Adobe Illustrator (it is hosted by a user named "adobe-webplatform"), to convert arc to cubic commands. It's also used in SVGO(ptimizer).
I'm still trying to decypher it, but the standard is actually pretty helpfull for that.
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.