Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get coordinates of svg group on drag with snap.svg

Tags:

svg

snap.svg

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.

like image 459
landland Avatar asked Nov 04 '13 18:11

landland


3 Answers

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

like image 161
Ian Avatar answered Nov 26 '22 09:11

Ian


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.

like image 27
Robert Longson Avatar answered Nov 26 '22 10:11

Robert Longson


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+')');
}
like image 24
Khyam Shahzad Avatar answered Nov 26 '22 09:11

Khyam Shahzad