简体   繁体   中英

Working with SVG polygon defined by user

i want to take the number of polygon's sides and makes the polygon accordingly. Is there any way through which i can take the number of polygon's sides and make a SVG polygon depending on that. Any way i can do this way ??

You can create svg polygons using the svg polygon element, all you need to calculate are the vertices of your polygon. Assuming you want to create a regular polygon (otherwise there is an unlimited amount of polygons with n sides, the vertices can be calculated as:

var vertices = [];
for(var i = 1; i <= n; i++) {
    vertices.push({
       x : Math.sin(2 * Math.PI * i / n),
       y : Math.cos(2 * Math.PI * i / n)
    });
}

 function makePolygon(posX, posY, numSides, size) { var points = []; for (var i = 0; i < numSides; i++) { points.push(posX + size * Math.sin(2 * Math.PI * i / numSides)); points.push(posY + size * Math.cos(2 * Math.PI * i / numSides)); } // Create a polygon element var poly = document.createElementNS("http://www.w3.org/2000/svg", "polygon"); poly.setAttribute("points", points.join(',')); // Add it to the SVG document.getElementById("mysvg").appendChild(poly); } makePolygon(250,250, 9, 200); 
 polygon { fill: yellow; stroke: blue; stroke-width: 10; } 
 <svg id="mysvg" width="500" height="500"></svg> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM