How to Use SVG cx and cy Attributes for Circles
In Scalable Vector Graphics (SVG), the cx and
cy attributes specify the exact horizontal and vertical
center coordinates of a <circle> element. By defining
the anchor point from which the circle’s radius expands, these two
attributes control where the circle is rendered within the SVG canvas
coordinate space.
The Coordinate System and Direction
The SVG coordinate system begins at the top-left corner of the
viewport, designated as (0, 0).
cx(Center X): Defines the center point along the horizontal X-axis. As the value ofcxincreases, the center of the circle shifts to the right.cy(Center Y): Defines the center point along the vertical Y-axis. As the value ofcyincreases, the center of the circle shifts downward.
Default Values
If either cx or cy is omitted from a
<circle> element, the browser defaults the missing
value to 0. If both are omitted, the center of the circle
will be positioned at the exact top-left origin (0, 0) of
the SVG container, resulting in only the bottom-right quadrant of the
circle being visible unless shifted by other transformations.
Relationship with the Radius
(r)
The cx and cy coordinates do not dictate
the outer edges of the circle; they strictly define the midpoint. The
circle’s boundary is determined by extending outward from
(cx, cy) in all directions by the value specified in the
r (radius) attribute.
For instance:
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="40" fill="navy" />
</svg>In this example: * The center of the circle is placed at
100 pixels from the left edge and 100 pixels
from the top edge. * With a radius r of 40,
the circle spans horizontally from x = 60
(cx - r) to x = 140 (cx + r), and
vertically from y = 60 (cy - r) to
y = 140 (cy + r).
Supported Units
While unitless numbers are treated as standard user space units
(typically equivalent to CSS pixels), cx and
cy also accept standard CSS length units and
percentages:
- Length units: Values such as
px,em, orrem(e.g.,cx="50px"). - Percentages: Values such as
cx="50%"andcy="50%", which dynamically center the circle relative to the width and height of the containing SVG viewport.