Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put label in the "center" of an SVG path

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 are in svg format and need to be parsed. Is there an easier way to determine the center of an svg polygon (maybe someone can point out a javascript library or a snippet)? I'm using Raphael javascript library to manipulate the svg, but it doesn't seem to go beyond the standard svg functionality.

like image 597
sol Avatar asked Nov 07 '09 03:11

sol


People also ask

How do I put text inside an SVG path?

To create SVG text that follows a path you use a <textPath> element in combination with a path you define inside <defs> tags. To refer to the path you'll use an xlink:href attribute on the <textPath> . Note: SVG 2.0 is dropping the xlink: and will simply use href to refer to the path.

How do I center a path in SVG?

You can change the svg viewBox attribute to center the path. This is especially useful if you have several paths in the svg, so you do not have to add a transform to each one. In your example that would be viewBox="0 15.674 144 144" , getting the y-offset the same way as in Pauls answer.


1 Answers

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.

like image 141
Erik Dahlström Avatar answered Oct 12 '22 10:10

Erik Dahlström