SVG & convert polygon/polyline to path

时间:2021-12-18 04:32:46

SVG & convert polygon/polyline to path

SVG Polygon/Polyline to Path Converter

https://codepen.io/xgqfrms/pen/VwLpbJq?editors=0010

SVG & convert  polygon/polyline to path

regex


const convertPolygonToPath = (svgStr = ``) => {
const result = svgStr
// close path for polygon
.replace(/(<polygon[\w\W]+?)points=(["'])([\.\d- ]+?)(["'])/g, "$1d=$2M$3z$4")
// dont close path for polyline
.replace(/(<polyline[\w\W]+?)points=(["'])([\.\d-, ]+?)(["'])/g, "$1d=$2M$3$4")
.replace(/poly(gon|line)/g, "path");
return result;
}

Convert Polygon to Path Data

https://css-tricks.com/snippets/javascript/convert-polygon-path-data/

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