使用javascript从任意SVG路径中提取x,y坐标
我想用变量替换SVG路径中的坐标。 (用javascript)。虽然svg路径可以有多种类型,但在具体示例上得到一些支持会很有帮助:
I want to replace the coordinates within a SVG path with variables. (with javascript). While svg path could be of many types it would be of great help to get some support on a concrete example:
d = "M27,0C27,21,4,34,-13,23C22,18,-27,9,-27,0";
我希望将此SVG路径转换为
I want this SVG path to be transformed into
var x = [];
var x[0] = 27; x[1] = ...
d = "M + x[0] + "," + y[0]
+ "C"
+ x[0] + "," + y[0] + ","
+ x[1] + "," + y[1] + ","
+ x[2] + "," + y[2] + ","
+ "C"
+ x[3] + "," + y[3] + ","
+ x[4] + "," + y[4] + ","
+ x[5] + "," + y[5];
所以我的问题是找到合适的javascript RegExp来提取所有变量,并使用它生成给定的SVG路径。
So my problem is to find the proper javascript RegExp to extract all the variables and by use of it generate the SVG path as given.
什么我实际上是创建一个代表给定svg的Javascript对象,我希望能够单独设置坐标。
What I actually do is creating a Javascript object representing a given svg and I want to able to set the coordinates individually.
任何帮助高度赞赏
thx,martin
thx, martin
更新:
旁边接受的答案在精彩的raphael.js库中也有一个非常方便的方法分析SVG路径
UPDATE: next to the accepted answer there is also a very handy method in the wonderful raphael.js library to analyze a SVG path
http://raphaeljs.com/ reference.html#Raphael.parsePathString
只需使用SVG DOM解析它此问题/答案中有更多详细信息但基本上你做了
Just use the SVG DOM to parse it there are more details in this question/answer but basically you do
var segments = path.pathSegList;
,它为您提供了一系列可以读取或写入的段和值,例如
and that gives you an array of segments and values you can read or write e.g.
segments.getItem(0).y = -10;