Drawing an Arc with Canvas/SVG

Ovilia
3 min readOct 18, 2019

If you wish to draw an arc in a Web page, then you should probably use Canvas or SVG.

To be more specific, an arc is a part of an ellipse. So we can imagine that, in order to define an arc, at least we need the following parameters:

The center of the ellipse, noted as x and y, long and short axis radius, noted as rx and ry, rotation, start angle, and end angle.

Canvas

Canvas has two corresponding API, arc and ellipse.

Arc is used for drawing an arc on a circle so the x radius and y radius are the same, and there is no rotation.

The last parameters of those two APIs are anticlockwise, which is a boolean to state if the arc is drawn from start to the end in anticlockwise. This is because, when we have start angle and end angle, there are actually two arcs fulfilling the condition so we need this parameter to define if to choose the anticlockwise one.

SVG

For SVG however, we need to provide the start point and the end point.

There are two parameters that we don’t know yet. One is called large-arc-flag, and the other is sweep-flag.

large-arc-flag is used to state if the arc is larger than half ellipse. This sounds easier than the Canvas design, but in fact, it’s more complicated because angles are not always between 0 to 2π. Different situations should be considered.

As for sweep-flag, it is a flag to state which arc to use. When we have the radius, rotation, start point, and end point, there are actually two ellipses that meet the condition and thus making four arcs.

According to large-arc-flag, we can exclude two of them. For example, if it is true, we can exclude the two small arcs. By definition, when sweep-flag is 1, the arc is in a positive angle, which is clockwise. So now, we can determine one certain arc.

Someone may ask why we should learn drawing an arc in such a hard way.

This is what we need to understand when creating ECharts, a JavaScript visualization tool supports both Canvas and SVG rendering.

Watch the YouTube video for more detailed explanation: https://studio.youtube.com/video/QXOPYyhifDc/edit

--

--