【问题标题】:parse d attribute in SVG path element解析 SVG 路径元素中的 d 属性
【发布时间】:2012-03-13 16:42:13
【问题描述】:

我正在尝试解析SVG Path元素中的d属性,目前发现fabric.js可以解析SVG,但是到现在我还是不知道怎么做。

我需要解析路径以获取其中的形状(线弧)并在其上绘制正方形,最重要的是返回这些正方形的属性。

知道如何使用fabric.js 做到这一点吗?或任何其他图书馆?还是有人有不同的方法?

下面的图像有一个矩形和一条线都有我在它们的边界上绘制的正方形,我试图在路径元素上做同样的事情

【问题讨论】:

    标签: javascript parsing svg path fabricjs


    【解决方案1】:

    我找到了这个

    var cmdRegEx = /[a-z][^a-z]*/ig;
    var commands = d.match(cmdRegEx);
    

    它可以获取每个命令及其参数,但您需要从空格中修剪每个命令

    【讨论】:

    • Nice... 可能会因标准格式表示法 (1e+0) 中的数字而失败,但我不确定这些数字在 SVG 中是否有效
    • 我很想改用这个正则表达式:(/[MLQTCSAZ][^MLQTCSAZ]*/gi(注意:未经测试)
    • 马克的反对是正确的。这些在 SVG 规范中被声明为有效,因此解析不应包含 e。 XBNF 具体是:command.floating-point-constant: fractional-constant exponent? |数字序列指数小数常数:数字序列? “。”数字序列 |数字序列“。”指数:(“e”|“E”)符号?数字序列
    【解决方案2】:

    根据 zeacuss 的回答和 Mark K Cowan 的建议,我正在使用:

    var cmdRegEx = /([MLQTCSAZVH])([^MLQTCSAZVH]*)/gi
    var commands = d.match(cmdRegEx);
    

    【讨论】:

      【解决方案3】:

      遇到同样的问题。您可以使用 regep /-?\d+/ig 仅生成数字,从字母和空格中分离出来。和逗号。

      【讨论】:

        【解决方案4】:

        Python 的svgpathtools 库可能对您的需求有用。这是它的功能列表(来自documentation):

        一些包含的工具:

        read, write, and display SVG files containing Path (and other) SVG elements
        convert Bézier path segments to numpy.poly1d (polynomial) objects
        convert polynomials (in standard form) to their Bézier form
        compute tangent vectors and (right-hand rule) normal vectors
        compute curvature
        break discontinuous paths into their continuous subpaths.
        efficiently compute intersections between paths and/or segments
        find a bounding box for a path or segment
        reverse segment/path orientation
        crop and split paths and segments
        smooth paths (i.e. smooth away kinks to make paths differentiable)
        transition maps from path domain to segment domain and back (T2t and t2T)
        compute area enclosed by a closed path
        compute arc length
        compute inverse arc length
        convert RGB color tuples to hexadecimal color strings and back
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-05-27
          • 2016-08-06
          • 1970-01-01
          • 2019-03-12
          • 2020-11-10
          • 2020-12-27
          • 2020-11-24
          • 2018-11-25
          相关资源
          最近更新 更多