Mon, 07 Sep 2009

How to Plot a Segment of a Circle with SVG

I wanted to generate some pie charts with SVG (for SVG::Plot),
and a search on the Internet quickly showed that I need paths for that. But the exact
usage remained unclear to me until I read the specs and did some
experimenting.

The way to go is:

Move to (M) the center of the circle

Line to (l) the starting point of the arc

Arc to (A) the end point of the arc

Close the path (z)

The start and end point of the arc can be calculated as

x = center_x + radius * cos(angle)
y = center_y + radius * sin(angle)

The parameters to the A command in the path are rx, ry,
axis-rotation large-arc-flag sweep-flag x y.

For our purposes
rx and ry need to be just the radius of the circle,
large-arc-flag is 1 if the difference between start angle and end
angle is larger than pi (or 180°).
sweep-flag is 1 if we assume that the start angle is smaller than the
end angle (and thus, since the SVG coordinate system has the positive y axis
downwards, plot clockwise).
x and y are the
coordinates of the end point.