Convert Polygon to Path Data

Avatar of Chris Coyier
Chris Coyier on

I’ve had to do this a few times recently so I thought I’d save the method. StackOverflow has a method that works great:

[].forEach.call(polys,convertPolyToPath);

function convertPolyToPath(poly){
  var svgNS = poly.ownerSVGElement.namespaceURI;
  var path = document.createElementNS(svgNS,'path');
  var points = poly.getAttribute('points').split(/\s+|,/);
  var x0=points.shift(), y0=points.shift();
  var pathdata = 'M'+x0+','+y0+'L'+points.join(' ');
  if (poly.tagName=='polygon') pathdata+='z';
  path.setAttribute('id',poly.getAttribute('id'));
  path.setAttribute('fill',poly.getAttribute('fill'));
  path.setAttribute('stroke',poly.getAttribute('stroke'));
  path.setAttribute('d',pathdata);

  poly.parentNode.replaceChild(path,poly);
}

Michael Schofield made a Pen to do it quick:

See the Pen Convert SVG Polygon to Path by Michael Schofield (@michaelschofield) on CodePen.

You put your own Polygon in the SVG above and then it gets replaced by a path in the DOM. You can DevTools inspect to get out the path data.

The purpose is, for example, you’re trying to animate from a shape with straight lines to a shape with curved lines. SVG software tools will output the former as a polygon, which is a different type of data that can’t animate natively to the path syntax.