How can I get the position of an object in Raphael? I can get the size using getBBox(), but there appears to be no way to get the position?
-
The problem may first be a definition of "position" of an object. If you mean the "gravity center" of the object, that must currently be computed by application code as it depends on the kind of object. Right now, it seems there is no library code to get the center of common shapes. For arbitrary shapes, I guess it may need be defined at the application level anyway, and the bounding box allows to compute it. If by position you mean the classical top-left corner position, the bounding box's (x, y) attributes is the result, as @b_dubb mentioned. – Eric Platon Jul 25 '12 at 07:05
5 Answers
getBBox() should give you position as well as x and y properties.
var bbox = el.getBBox();
alert([bbox.x, bbox.y]);

- 1,200
- 6
- 10
-
5thanks but it would be great if you could add those tips in the documentation of raphaeljs. – Mermoz Feb 25 '11 at 09:50
-
6
getBBox() returns an object with 5 properties. they are:
- x
- y
- width
- height
- toString()
if you set getBBox( false ) it will return coordinate data for the object's position AFTER a transformation. set it to getBBox( true ) to return coordinates for the object prior to transformation
use like this ...
paper.Raphael(10,10,300,300);
circle.paper( 30, 55, 15 );
var circleBBox = circle.getBBox( false );
edit: just downloaded R 2.1 and i believe it has added x2 and y2 to the properties returned by getBBox()

- 444
- 13
- 29
Depending on what kind of shape it is, the documentation seems to say it can be accessed using the .attr()
function. So, if it's a circle...
var x = myCircle.attr('cx'); //cx is the center-x-coordinate of the circle
var y = myCircle.attr('cy'); //same, for y
var r = myCircle.attr('r'); //Radius of circle.
A square would have attr
s of x, y, width, height. Check the documentation for more info.

- 3,032
- 20
- 14
you may also access the x and y values this way:
var x = myCircle.attrs.x;
var y = myCircle.attrs.y

- 31
- 1
attributes x, y are those within the set. The issue here is that if the set gets translated somewhere else, the x and y given in by .getBBOx() do not account for the translation.
Raphael.transformPath(path, transform) can help by applying the same transforms that the set has...
to translate that point you can:
tp = Raphael.transformPath("M"+x+","+y, set.attr('transform'))
x = tp[0][1]
y = tp[0][2]

- 1