xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

SVG & convert polygon/polyline to path

SVG Polygon/Polyline to Path Converter

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

regex


const convertPolygonToPath = (svgStr = ``) => {
  const result = svgStr
    // close path for polygon
    .replace(/(<polygon[wW]+?)points=(["'])([.d- ]+?)(["'])/g, "$1d=$2M$3z$4")
    // dont close path for polyline
    .replace(/(<polyline[wW]+?)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);
}


原文地址:https://www.cnblogs.com/xgqfrms/p/12398853.html