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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With