Get coordinates of svg group on drag with snap.svg

landland picture landland · Nov 4, 2013 · Viewed 10.7k times · Source

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.

Answer

Ian picture Ian · Nov 4, 2013

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