Samul
Samul

Reputation: 2019

getPointAtLength with SVG not working correctly

I have a huge SVG file and all of its data is in one single element. It's something like this:

<path d="M724 1541c133,-400 36,-222 334,-520 76,-75 440,-37 557,-37 145,291 111,
    -32 111,445 0,344 -3,260 483,260 457,0 177,-111 409,-111 0,-62 0,-124 0,-186 
    -368,0 190,-111 -409,-111 -143,0 2,40 -148,223 ... huge SVG "/>

I am converting this huge SVG to polylines using the function "getPointAtLength"as this guy answered my question: https://stackoverflow.com/a/39405746/2934699

The problem is this: this SVG is not a continuous one, it has some shapes (rectangles, circles...) which are not connected. But when I use the method of the link above all my shapes get connected. Is there someway to solve this problem?

Upvotes: 1

Views: 2702

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101800

There are two possible approaches I can think of to solve your problem.

1. Quick and dirty

As you loop through the path, calculate the distance from the last path point. If that distance exceeds some limit, you can consider that you have stepped into a new subpath. So begin a new polyline.

2. More accurate but trickier

Preprocess the path using the mypath.pathSegList property. That call returns a list of the path commands in the path.

  1. Then loop through the pathSegList and take note of where each move command is. These mark the start of each subpath
  2. As you loop through flattening the path, call the mypath.getPathSegAtLength() function. It returns the index of the pathseg entry at that length.
  3. Compare that with the data you recorded in step 1 to see if you have moved into a new subpath
  4. If you have, start a new polyline (or polygon)

One complication is that Chrome has deprecated support for the pathSegList property, and have instead moved to the new SVG2 API for this (mypath.getPathData()). Fortunately there is a polyfill for Chrome to add back support for the old API. Or you can switch to the new API and use a different polyfill so that the new API works on older browsers.

You can find details on the two polyfills here

Upvotes: 3

Related Questions