views:

431

answers:

2

Hi

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.

A: 

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.

Randaltor
Sorry, for not clearly phrasing my question. The problem is more about how to get the coordinates from the path's d-attribute which is in this format<path d="M 100 100 L 300 100 L 200 300 z" fill="red" stroke="blue" stroke-width="3" /> in order to calculate the center or to find a javascript library that does that without me parsing the attribute according to the svg spec.
sol
The first problem to solve first is to convert the svg into polygon first. I have been searching for a code to convert the svg paths into polygons but couldn't find one. Maybe have to dig-up on the source codes of svg projects
ivanceras
A: 

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.

Erik Dahlström