使用 javaScript 解析 SVG 路径字符串以提取初始 x,y 坐标的最简单方法

joj*_*ohn 7 javascript svg

path[1].innerHTML 
Run Code Online (Sandbox Code Playgroud)

回报

  <path d="M 5,10 l0,0 l 15 ,0l0,15l-15,0l0,-15 z" ....
Run Code Online (Sandbox Code Playgroud)

M 之后的前 2 位数字是 SVG 路径起点的 x,y 坐标。

path[1].innerHTML.substr(10,2)
Run Code Online (Sandbox Code Playgroud)

返回 x 坐标 (5) 和

path[1].innerHTML.substr(13,2) 
Run Code Online (Sandbox Code Playgroud)

返回正确的 y 坐标。问题是这些值可能是一位、两位或三位数字,这将破坏 substr() 的执行方式。

Rap*_*Mex 1

一种简单的方法是根据已知格式分割字符串,并在您期望的位置获取 x,y:

const path = "M 5,10 l0,0 l 15 ,0l0,15l-15,0l0,-15 z",
      splitted = path.split(" ")[1].split(","),
      x = splitted[0],
      y = splitted[1];
console.log(x,y);
Run Code Online (Sandbox Code Playgroud)

您也可以使用正则表达式,但它可能不会更简单。