Home > Enterprise >  Extract coordinates from SVG String
Extract coordinates from SVG String

Time:02-01

  let path_string='<path transform="matrix(1,0,0,-1,0,600)" stroke-width=".074" stroke-linecap="round" stroke-linejoin="round" fill="none" stroke="#000000" d="M 274.75 301.4 L 275.41 303.36 L 275.41 307.28 L 289.11 293.57 "/>'

Above shows an SVG path code as a string, I want to extract the x and y coordinates of the path and store it in array. The pattern is that all the coordinate numbers are seperated by spaces before and after.

For example, the above code when used as input should output

x_coor_arr=[274.75,275.41,275.41,289.11];

y_coor_arr=[301.4,303.36,307.28,293.57];

How do I solve this efficiently?

CodePudding user response:

You can get the d attribute from the path element and then:

var svgRaw = 'M 274.75 301.4 L 275.41 303.36 L 275.41 307.28 L 289.11 293.57 ';
  svgRaw = svgRaw.split(' ');

  var coorX = [];
  var coorY = [];

  svgRaw = svgRaw.filter((item) => !['M', 'L', ''].includes(item));
  svgRaw.forEach((item, index = 1) => {
    if (index % 2 === 0) {
      return coorX.push(item);
    }

    return coorY.push(item)
  });

  console.log(coorX, coorY);

  • Related