7

I'm brand new to svg and thought I would try out snap svg. I have a group of circles that I am dragging around, and am looking to get the coordinates of the group. I am using getBBox() to do this, but it isn't working as I would expect. I would expect getBBox() to update its x and y coordinates but it does not seem to do that. It seems simple but I think I am missing something. Here's the code

var lx = 0,
  ly = 0,
  ox = 0,
  oy = 0;
  moveFnc = function(dx, dy, x, y) {
      var thisBox = this.getBBox();
      console.log(thisBox.x, thisBox.y, thisBox);
      lx = dx + ox;
      ly = dy + oy;
      this.transform('t' + lx + ',' + ly);
  }
  startFnc = function(x, y, e) {  }
  endFnc = function() {
      ox = lx;
      oy = ly;  
      console.log(this.getBBox());
  };

var s = Snap("#svg");
var tgroup = s.group();
tgroup.add(s.circle(100, 150, 70), s.circle(200, 150, 70));
tgroup.drag(moveFnc, startFnc, endFnc);

The jsfiddle is at http://jsfiddle.net/STpGe/2/

What am I missing? How would I get the coordinates of the group? Thanks.

landland
  • 2,117
  • 3
  • 20
  • 26

3 Answers3

9

As Robert says it won't change. However getBoundingClientRect may help.

this.node.getBoundingClientRect(); //from Raphael

Jsfiddle here showing the difference http://jsfiddle.net/STpGe/3/.

Edit: Actually I'd be tempted to go here first, I found this very useful Get bounding box of element accounting for its transform

Community
  • 1
  • 1
Ian
  • 13,724
  • 4
  • 52
  • 75
7

Per the SVG specification, getBBox gets the bounding box after transforms have been applied so in the co-ordinate system established by the transform attribute the position is the same.

Imagine like you drew the shape on graph paper setting a transform moves the whole graph paper but when you look at position of the shape on the graph paper it hasn't changed, it's the graph paper that's moved but you're not measuring that.

Robert Longson
  • 118,664
  • 26
  • 252
  • 242
1

Try to use the group.matrix object to get x and y coordinate of group object.

moveFnc = function(dx, dy, x, y, event) {
  lx = this.matrix.e;
  ly = this.matrix.f;
  this.transform('translate(' + lx + ',' + ly+')');
}
Khyam Shahzad
  • 139
  • 1
  • 5
  • I get undefined for this.matrix and group.matrix. Can you show via jsfiddle or point me to a link in the docs? thanks – landland Dec 11 '13 at 16:42
  • I suspect that you are yet to do a transformation on the group. Translate it first and then try again – CF5 Feb 18 '16 at 18:28