Playing with SVG
by Sean Furrh
HTML
<svg width="800" height="3000" id="svg">
</svg>
JavaScript
function addRegularPolygonToSVG(svgElement, cx, cy, radius, sides, attributes = {}) {
if (sides < 3) {
console.error("Polygon must have at least 3 sides.");
return;
}
const polygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
// Calculate the points
const angleStep = (2 * Math.PI) / sides;
const points = [];
for (let i = 0; i < sides; i++) {
const angle = i * angleStep - Math.PI / 2; // Rotate to start from the top
const x = cx + radius * Math.cos(angle);
const y = cy + radius * Math.sin(angle);
points.push([x, y]);
}
const pointsString = points.map(p => p.join(',')).join(' ');
polygon.setAttribute("points", pointsString);
// Apply optional attributes
for (const [key, value] of Object.entries(attributes)) {
polygon.setAttribute(key, value);
}
svgElement.appendChild(polygon);
}
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
ready(new function(){
let svg = document.getElementById("svg");
addRegularPolygonToSVG(svg, 75, 75, 20, 8, attributes = {})
});