0

I receive arbitrary path data that is sometimes in the 10s of thousands positions.

How would i normalize it so that the top and left positions are at 0 x 0?

So for a Path that was created at 1000x1000 would be:

M 1000 1000 L 1000 1050 L 1050 1100 Z

and after normalization would be:

M 0 0 L 0 50 L 50 100 Z

Example code:

path.pathData // M 1000x1000 L 1000x1050 L 1050x1100 Z
path.normalizeToPosition(0,0);
path.pathData // M 0x0 L 0x50 L 50x100 Z

I've seen this answer and it looks close to what I want but the difference is I want the top and left most positions to be 0x0.

To put it another way I want the viewBox to always start with "0 0" and the vector path top and left to be completely inside the viewBox area no matter what the current path data is.

Another example. If the path data is:

M -1000 -1000 L -1000 -1050 L -1050 -1100 Z

The function would modify it to

M 0 0 L 0 50 L 50 100 Z
1.21 gigawatts
  • 16,517
  • 32
  • 123
  • 231

1 Answers1

0

You can use the SVG DOM path API. You'll need a polyfill on Chrome though.

var path = document.getElementById("path");

var segments = path.pathSegList;
var len = segments.numberOfItems;

var newPath = ""

for (var i=0; i<len; ++i) {
  var pathSeg = segments[i];
  switch(pathSeg.pathSegTypeAsLetter){
  case 'M':
  case 'L':
    newPath += `${pathSeg.pathSegTypeAsLetter} ${pathSeg.x - segments[0].x} ${pathSeg.y - segments[0].y} `
    break;
  case 'Z':
    newPath += 'Z';
    break;
  }
}

console.log(newPath);
path.setAttribute("d", newPath);
<svg>
    <path id="path" d="M 1000 1000 L 1000 1050 L 1050 1100 Z"/>
</svg>
Robert Longson
  • 118,664
  • 26
  • 252
  • 242