James Hollingworth
James Hollingworth

Reputation: 14210

RaphaelJs : How to add some text to an area defined by a path?

I have an SVG image of the united states which I've drawn with a little bit of help from Raphaël js:

http://jsfiddle.net/zCRkg/2/

What I want to do is place some text to the right of each state when you hover over it. The problem is that, since each state is a path, its quite difficult to determine the x & y coordinates for where to place the label.

So, does anyone know a way of calculating the centre of a path using Raphaël? If failing that anyone know how to do this given a an array of vectors?

Upvotes: 1

Views: 1866

Answers (2)

Jarkko Laine
Jarkko Laine

Reputation: 116

What you're looking for is the getBBox function in Raphaël. It will give you a bounding box object that you can use to calculate the central point of the path:

var bbox = st.getBBox();
var text = r.text(bbox.x + bbox.width/2, bbox.y + bbox.height/2, "Foo");

I forked your fiddle and made it show a static text in the middle of each state on hover. Picking up the state name from your data is left as an exercise.

Upvotes: 3

Andrew Bullock
Andrew Bullock

Reputation: 37378

the average of the difference between each coord should give you the centre, but thats probably not the most efficient way

Upvotes: 1

Related Questions