Put label in the “center” of an SVG path

前端 未结 3 1332
萌比男神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条回答
  •  旧时难觅i
    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.

提交回复
热议问题