How to Create a Circle in SVG: Simple Guide with Examples
To create a circle in SVG, use the
<circle> element with attributes cx and cy for the center coordinates, and r for the radius. You can style the circle using stroke and fill attributes.Syntax
The <circle> element in SVG requires three main attributes:
cx: The x-coordinate of the circle's center.cy: The y-coordinate of the circle's center.r: The radius of the circle.
You can also add stroke to set the border color and fill to set the inside color.
html
<circle cx="50" cy="50" r="40" stroke="black" fill="red" />
Example
This example shows a red circle with a black border centered at (50, 50) with a radius of 40 pixels inside an SVG canvas of 100 by 100 pixels.
html
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"> <circle cx="50" cy="50" r="40" stroke="black" fill="red" /> </svg>
Output
A red circle with a black border centered in a 100x100 pixel square.
Common Pitfalls
Common mistakes when creating circles in SVG include:
- Forgetting to set
cxandcy, which defaults the center to (0,0) and may place the circle outside the visible area. - Setting
rto zero or a negative value, which will not display a circle. - Not specifying
strokeorfill, which can make the circle invisible if both default to transparent.
html
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"> <!-- Wrong: radius zero, circle won't show --> <circle cx="50" cy="50" r="0" stroke="black" fill="red" /> <!-- Right: radius set to 40 --> <circle cx="50" cy="50" r="40" stroke="black" fill="red" /> </svg>
Output
Only the second circle with radius 40 is visible as a red circle with black border.
Quick Reference
| Attribute | Description | Example |
|---|---|---|
| cx | X coordinate of circle center | cx="50" |
| cy | Y coordinate of circle center | cy="50" |
| r | Radius of the circle | r="40" |
| stroke | Color of the circle border | stroke="black" |
| fill | Color inside the circle | fill="red" |
Key Takeaways
Use with cx, cy, and r attributes to create a circle in SVG.
Always set cx and cy to position the circle inside the SVG canvas.
Radius (r) must be positive to see the circle.
Use stroke and fill to style the circle's border and fill colors.
Without proper attributes, the circle may not appear or be visible.