Last updated
SVG Basic Shapes
SVG provides six basic shape elements: rect, circle,
ellipse, line, polyline, and polygon.
Each has specific attributes for positioning and sizing. For complex shapes,
the path element is used instead.
Shape Attribute Reference
| Shape | Key Attributes |
|---|---|
| rect | x, y, width, height, rx (corner radius), ry |
| circle | cx (center x), cy (center y), r (radius) |
| ellipse | cx, cy, rx (x-radius), ry (y-radius) |
| line | x1, y1 (start), x2, y2 (end) |
| polyline | points (space-separated x,y pairs) |
| polygon | points (auto-closes the shape) |
Generating Shapes Programmatically
JavaScript
const SVG_NS = 'http://www.w3.org/2000/svg';
function createShape(type, attrs) {
const el = document.createElementNS(SVG_NS, type);
Object.entries(attrs).forEach(([k, v]) => el.setAttribute(k, v));
return el;
}
const svg = document.querySelector('svg');
// Add a rounded rectangle
svg.appendChild(createShape('rect', {
x: 10, y: 10, width: 100, height: 60,
rx: 8, fill: '#3498DB', stroke: '#2980B9', 'stroke-width': 2
}));
// Add a regular hexagon using polygon
function hexagonPoints(cx, cy, r) {
return Array.from({length: 6}, (_, i) => {
const a = (Math.PI / 3) * i - Math.PI / 6;
return `${(cx + r * Math.cos(a)).toFixed(1)},${(cy + r * Math.sin(a)).toFixed(1)}`;
}).join(' ');
}
svg.appendChild(createShape('polygon', {
points: hexagonPoints(150, 50, 40),
fill: '#2ECC71'
}));