Put label in the “center” of an SVG path

前端 未结 3 1296
萌比男神i
萌比男神i 2021-02-05 14:11

I\'m trying to draw a label on a polygon of an svg file. The problem I\'m facing is to find out roughly the center of this polygon to place the label, as the path\'s coordinates

相关标签:
3条回答
  • 2021-02-05 14:22

    Insert a text tag inside the svg and position it by calculating the width and hight

     <svg width="447pt" height="559pt" viewBox="0 0 894 1118" version="1.1" xmlns="http://www.w3.org/2000/svg">
        ............
        ............
    
       <text x="450" y="300" font-family="Verdana" font-size="15" fill="red" >
            Text To Show
       </text>
    </svg>
    
    0 讨论(0)
  • 2021-02-05 14:23

    The simplest thing you could try doing is to calculate the center by taking the average of all the points in the polygon. It should work for all but the most irregular of polygons. I've used the same algorithm to good effect in my programs.

    Best of luck.

    0 讨论(0)
  • 2021-02-05 14:32

    You could try the following approximation for doing something similar to the polygon suggestion, based on SVG DOM methods:

    var totalPathLength = pathelm.getTotalLength();
    var step = totalPathLength / 100;
    for(var dist=0; dist < totalPathLength; dist+=step)
    {
      var pt = pathelm.getPointAtLength(dist);
      addToAverage(pt.x, pt.y);
    }
    

    I think the simplest approach is to use the center of the path element's boundingbox (pathelm.getBBox()), that's simpler than the polygon suggestion.

    0 讨论(0)
提交回复
热议问题