simplest way to use javaScript to parse SVG path s

2019-08-06 10:23发布

path[1].innerHTML 

returns

  <path d="M 5,10 l0,0 l 15 ,0l0,15l-15,0l0,-15 z" ....

The first 2 digits after M are the x,y coordinates for the starting point of the SVG path.

path[1].innerHTML.substr(10,2)

returns the x cordinate (5) and

path[1].innerHTML.substr(13,2) 

returns the correct y coordinate. The problem is the values may be single or double or triple digit numbers which will break the substr() way of doing it.

3条回答
forever°为你锁心
2楼-- · 2019-08-06 10:52

A simple way is to split your string based on its known format, and get your x,y where you expect them:

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);

You can also use regex, but it may not be simpler.

查看更多
干净又极端
3楼-- · 2019-08-06 10:55

Use the pathSegList interface:

var path = document.querySelector('path');
var moveto =  path.pathSegList[0]; // always the first movoto command
var x = movoto.x, y = moveto.y
查看更多
我命由我不由天
4楼-- · 2019-08-06 11:02

Browsers have a parser built in, use it or you'll just spend your life on wheel reinventing and bugfixing.

Note for Chrome, you'll need to use a polyfill

var path = document.getElementById("p");
var item1 = path.pathSegList[0];
alert("first co-ordinate is " + item1.x + ", " + item1.y);
<svg>
    <path id="p" d="M 5,10 l0,0 l 15 ,0l0,15l-15,0l0,-15 z"/>
</svg>

查看更多
登录 后发表回答