javascript 使用javascript从任意SVG路径中提取x,y坐标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19832534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extract x,y coordinates from arbitrary SVG path with javascript
提问by dorjeduck
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:
我想用变量替换 SVG 路径中的坐标。(使用javascript)。虽然 svg 路径可以有多种类型,但在具体示例上获得一些支持会很有帮助:
d = "M27,0C27,21,4,34,-13,23C22,18,-27,9,-27,0";
I want this SVG path to be transformed into
我希望将此 SVG 路径转换为
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];
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.
所以我的问题是找到合适的 javascript RegExp 来提取所有变量,并通过使用它生成给定的 SVG 路径。
What I actually do is creating a Javascript object representing a given svg and I want to able to set the coordinates individually.
我实际做的是创建一个表示给定 svg 的 Javascript 对象,我希望能够单独设置坐标。
Any help highly appreciated
任何帮助高度赞赏
thx, martin
谢谢,马丁
UPDATE: next to the accepted answer there is also a very handy method in the wonderful raphael.js library to analyze a SVG path
更新:在已接受的答案旁边,在精彩的 raphael.js 库中还有一个非常方便的方法来分析 SVG 路径
回答by Robert Longson
Just use the SVG DOM to parse it there are more details in this question/answerbut basically you do
只需使用 SVG DOM 来解析它,这个问题/答案中有更多细节,但基本上你是这样做的
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;
回答by Manolo
This could be your regex:
这可能是您的正则表达式:
var newd = d.match(/(^[0-9]+,)|(^,[0-9]+)$/g);
var arrayd = newd.split(",");
回答by Tafari
I'm just learning JavaScript so I'm unable to help with the transforming thing, but this regex should help:
我只是在学习 JavaScript,所以我无法帮助进行转换,但是这个正则表达式应该会有所帮助:
\-?\d+
It captures all of the coordinates from the string you have provided, while avoiding characters [a-zA-Z]
.
它从您提供的字符串中捕获所有坐标,同时避免使用字符[a-zA-Z]
。
But I can provide some more-or-lesscode in Javawhich would do the job.
但是我可以提供一些或多或少的Java代码来完成这项工作。
Pattern p = Pattern.Compile("\-?\d+");
Matcher m = p.matcher(yourPathString);
while(m.Find())
\add the match to your new table or something you want