Convert Polygon to Path Data

Submitted by:Jhon Smith

Date added:21 December, 2016

Category:JavaScript

Convert Polygon to Path Data code snippet by Chris Coyier

Tags: convert polygon , path data

Code Snippet:

[].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);
}
 
 

Comments