Search code examples
javascriptsvgpolygon

Converting svg path to polygon in javascript


i am trying to convert an svg path to an svg polygon in javascript. i found this function to crawl along the path and extract its coordinates.

    var length = path.getTotalLength();
    var p=path.getPointAtLength(0);
    var stp=p.x+","+p.y;
    
    for(var i=1; i<length; i++){
    
        p=path.getPointAtLength(i);
        stp=stp+" "+p.x+","+p.y;
        
    }

this works but it returns some hundreds of points for a polygon that has only six points originally. how would i get only the necessary points (all paths are straight lines, no curves)

var path = $.find("path")[0];

var len = path.getTotalLength();
var p = path.getPointAtLength(0);
var stp = p.x + "," + p.y;
var newp;

for (var i = 1; i < len; i++) {
  newp = path.getPointAtLength(i);
  if (newp.x != p.x && newp.y != p.y) {
    p = newp;
  } else {
    continue;
  }
  stp = stp + " " + p.x + " " + p.y;

}

$('#poly').text(stp);
pre {
  display: block;
  white-space: pre-wrap;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="425.2px" height="303.31px" viewBox="0 0 425.2 303.31" enable-background="new 0 0 425.2 303.31" xml:space="preserve">
<g>
    <path id="path" fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M256.768,227.211h-33.013l4.902-65.682l-40.357,59.06
        l-26.654-37.931l0.292-0.298L264.865,77.415L256.768,227.211z M224.833,226.211h30.987l7.903-146.205L162.942,182.764
        l25.346,36.069l41.643-60.94L224.833,226.211z"/>
</g>
</svg>

<code>
<pre id="poly">
</pre>
</code>


Solution

  • ok got it.. the function getPathSegAtLength() returns the number of the actual path segment. with that it's easy then.

        var len = path.getTotalLength();
        var p=path.getPointAtLength(0);
        var seg = path.getPathSegAtLength(0);
        var stp=p.x+","+p.y;
    
        for(var i=1; i<len; i++){
    
            p=path.getPointAtLength(i);
    
            if (path.getPathSegAtLength(i)>seg) {
    
            stp=stp+" "+p.x+","+p.y;
            seg = path.getPathSegAtLength(i);
    
            }
    
        }