将SVG多边形转换为路径 [英] Convert SVG polygon to path

查看:119
本文介绍了将SVG多边形转换为路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Raphael.JS中有一个需要处理的相当大的行政部门SVG文件(它有600个多边形,权重为1.2 Mb).

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).

现在,我需要将这些多边形转换为路径,以便它可以在Raphael中使用.很棒的 poly2path工具可以做到这一点,但是它不支持任何批处理命令,因此每个多边形相对于其他多边形的位置都会丢失.

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.

您知道有什么工具可以将SVG多边形转换为路径吗? (我还有用于导出SVG的AI文件.)

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).

非常感谢

推荐答案

  1. 在网络浏览器中打开您的SVG.
  2. 运行以下代码:

  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);
}

  • 使用浏览器的开发人员工具(或Firebug),在元素上使用复制为HTML"(或复制SVG")将修改后的源代码保存到剪贴板上.

  • 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.

    粘贴到新文件中并欣赏.

    Paste into a new file and enjoy.

    我在我的网站上有一个上述方法的演示(略作修改):
    http://phrogz.net/svg/convert_polys_to_paths.svg

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

    该页面上使用了两种方法;一个(如上所述)使用基于字符串的技术来获取和设置点;另一个使用SVG DOM来访问点和设置路径命令.

    正如@Interactive在评论中指出的那样,您可以通过以下方式通过纯文本转换来实现此目的:

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

    1. 将所有<polyline<polygon转换为<path
    2. 将所有points="更改为d="M
    3. 对于任何<polygon>元素,您需要添加z作为d属性的最后一个字符,以将最后一个点连接到第一个点.例如:

    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"/> 
    

    成为

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

  • 此"hack"之所以有效,是因为规范声明 moveto命令(Mm)后跟多个坐标是合法的,第一个之后的所有坐标都解释为lineto命令.

    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.

    这篇关于将SVG多边形转换为路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆