Working with SVG polygon defined by user

时间:2015-05-08 09:53:33

标签: javascript angularjs svg snap.svg

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 ??

1 个答案:

答案 0 :(得分:1)

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>