Pergunta

i need to know if a svg path can be converted to svg polyline or not.
i found the javascript code which convert a path to a polygon:

function pathToPolygon(path,samples){
  if (!samples) samples = 0;
  var doc = path.ownerDocument;
  var poly = doc.createElementNS('http://www.w3.org/2000/svg','polygon');

  // Put all path segments in a queue
  for (var segs=[],s=path.pathSegList,i=s.numberOfItems-1;i>=0;--i) segs[i] = s.getItem(i);
  var segments = segs.concat();

  var seg,lastSeg,points=[],x,y;
  var addSegmentPoint = function(s){
    if (s.pathSegType == SVGPathSeg.PATHSEG_CLOSEPATH){

    }else{
      if (s.pathSegType%2==1 && s.pathSegType>1){
        // All odd-numbered path types are relative, except PATHSEG_CLOSEPATH (1)
        x+=s.x; y+=s.y;
      }else{
        x=s.x; y=s.y;
      }
      var lastPoint = points[points.length-1];
      if (!lastPoint || x!=lastPoint[0] || y!=lastPoint[1]) points.push([x,y]);
    }
  };
  for (var d=0,len=path.getTotalLength(),step=len/samples;d<=len;d+=step){
    var seg = segments[path.getPathSegAtLength(d)];
    var pt = path.getPointAtLength(d);
    if (seg != lastSeg){
      lastSeg = seg;
      while (segs.length && segs[0]!=seg) addSegmentPoint( segs.shift() );
    }
    var lastPoint = points[points.length-1];
    if (!lastPoint || pt.x!=lastPoint[0] || pt.y!=lastPoint[1]) points.push([pt.x,pt.y]);
  }
  for (var i=0,len=segs.length;i<len;++i) addSegmentPoint(segs[i]);
  for (var i=0,len=points.length;i<len;++i) points[i] = points[i].join(',');
  poly.setAttribute('points',points.join(' '));
  return poly;
}

i m a beginner at js and do not understand this line: var seg,lastSeg,points=[],x,y;

it works nice, but it draws a frame around the path line. but i do not want a frame, i want to convert path to point set, polyline. is it possible thanks

Foi útil?

Solução

A polyline is an unclosed polygon, it is possible to have polylines that start and finish at the same point, which makes them equal to a polygon.

Although paths have lists of points, you can specify if the points are linked with straight lines or various other curves.

I'm a bit confused by your question : "it works nice, but it draws a frame around the path line. but i do not want a frame"

I think the problem here is some styling attributes rather than the type of object.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top