Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
777 views
in Technique[技术] by (71.8m points)

raphael - Convert SVG polygon to path

I have a fairly large SVG file of administrative subdivisions that I need to work with in Raphael.JS (it has 600 polygons and weights 1.2 Mb).

Now, I need to convert these polygons to paths so that it works in Raphael. The great poly2path tool does that, but it doesn't support any batch command, so that each polygon's position relative to the others is lost.

Do you know of any tool to convert SVG polygons to paths? (I also have the AI file which was used to export the SVG).

Many thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. Open your SVG in a web browser.
  2. Run this code:

    var polys = document.querySelectorAll('polygon,polyline');
    [].forEach.call(polys,convertPolyToPath);
    
    function convertPolyToPath(poly){
      var svgNS = poly.ownerSVGElement.namespaceURI;
      var path = document.createElementNS(svgNS,'path');
      var pathdata = 'M '+poly.getAttribute('points');
      if (poly.tagName=='polygon') pathdata+='z';
      path.setAttribute('d',pathdata);
      poly.parentNode.replaceChild(path,poly);
    }
    
  3. Using the Developer Tools (or Firebug) of the browser, use "Copy as HTML" (or Copy SVG) on the element to get the modified source onto the clipboard.

  4. Paste into a new file and enjoy.

I have a demo of the above method (slightly modified) on my website:
http://phrogz.net/svg/convert_polys_to_paths.svg

There are two methods in use on that page; one (like the above) uses string-based techniques to get and set the points; the other uses the SVG DOM for accessing points and setting path commands.


As noted by @Interactive in the comments, you can do this via text-only transformations by:

  1. Convert all <polyline and <polygon to <path
  2. Change all points=" to d="M
  3. For any elements that were <polygon>, you need to add z as the last character of the d attribute to connect the last point to the first. For example:

    <polygon points="1,2 3,-4 5,6"/> 
    

    becomes

    <path d="M1,2 3,-4 5,6z"/> 
    

This 'hack' works because the specifications declare that a moveto command (M or m) followed by multiple coordinates is legal, with all coordinates after the first interpreted as lineto commands.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...