2012-02-23 93 views
4

我試圖解析SVG Path元素中的d屬性,到目前爲止我發現fabric.js可以解析SVG,但直到現在我仍然不知道如何。在SVG路徑元素中解析d屬性

我需要解析路徑以獲取其中的形狀(直線弧)並在其上繪製正方形,最重要的是返回這些正方形的屬性。

任何想法如何做到這一點使用fabric.js ??或任何其他庫?還是有人有不同的方法?

下面的圖片有一個矩形和線都有,我對他們的邊界畫了廣場,我試圖做同樣的路徑元素rectangle and line with boundaries

回答

3

上,我發現這個

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

它可以得到每個命令與它的參數,但你需要從空間修剪每個命令

+0

尼斯...可能會失敗,以標準的形式符號(1E + 0)的數字,但我不確定這些在SVG中是否有效 – 2015-03-06 13:50:33

+0

我很想用這個正則表達式代替:'(/ [MLQTCSAZ] [^ MLQTCSAZ] */gi'(注意:未經測試) – 2015-03-06 13:53:17

+1

Mark的反對是正確的。這些在SVG規範中聲明爲有效,因此這種解析不應包含e .XBNF具體爲: command.floating-point-constant: 分數常數指數? |數字序列指數 分數常數: 數字序列? 「」數字序列 |數字序列「。」 指數: (「e」|「E」)符號?數字序列 – Tatarize 2016-06-15 17:54:23

2

蓋印到相同的問題。你可以使用regep/- ?\ d +/ig,它只產生數字,從字母,空白條紋。和逗號。

+0

也刪除了小數點! '/ - ?\ d +(。\ \ d +)/ ig' – pete 2012-05-23 00:04:16

1

基於zeacuss答案和前標記考恩建議,我使用的是:

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

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