1

I am looking for a function that can convert something like:

var points="270,328 270,376 342,376 342,368 358,368 358,320 314,320 298,336 278,336"

into the SVG format for paths, I have seen this question / answer, but I get an error :Uncaught TypeError: Cannot read property 'ownerSVGElement' of undefined. This is because I am putting my var points into that function, which is not designed for that, I think it needs the full xml or something.

Any suggestions are great, especially to force illustrator to export paths instead of polygons!

Thanks!

Community
  • 1
  • 1
dezman
  • 18,087
  • 10
  • 53
  • 91

1 Answers1

11
var points="270,328 270,376 342,376 342,368 358,368 358,320 314,320 298,336 278,336"

var p = points.split(/\s+/);
var path = "";
for( var i = 0, len = p.length; i < len; i++ ){
    path += (i && "L" || "M") + p[i]
}

console.log( path )
=> M270,328L270,376L342,376L342,368L358,368L358,320L314,320L298,336L278,336 
Andrei Nemes
  • 3,062
  • 1
  • 16
  • 22
  • I am getting this sometimes: M630,352L630,306LLLLL704,314L704,356L718,356L718,384L702,368L646,368L646,360L638,360L638,352LLL, and arent they supposed to end with a 'z'? – dezman Apr 26 '13 at 22:03
  • 3
    Updated my answer. Also, you are only supposed to add a z if you want to close the path. – Andrei Nemes Apr 27 '13 at 00:14
  • 2
    Thanks, it works. But this could be more readable. `path = 'M' + points.replace(/\s+/g, 'L');` – Yuriy Yakubskiy Mar 06 '15 at 15:05
  • 1
    @YuriyYakubskiy I would suggest to use `split`/`join`, so you can ommit the `g`-modifier. Also, don't forget to trim the points before replace: `'M' + points.trim().split(/\s+/).join('L');` – yckart Feb 06 '16 at 19:51