olibou
olibou

Reputation: 1

snap.svg wrong drag move when in a group scaled?

With Snap.svg I try to drag an element which is within a group that has been scaled, and the movement does not follow the mouse (go twice as fast) . Here is my example code :

var s = Snap('#test');

var start = function() {this.data('o', this.transform().local );}
var move = function(dx,dy) {
var o = this.data('o');
    this.attr({transform: o + (o ? "T" : "t") + [dx, dy]});
}


var c1 = s.circle(60,150,10).attr({fill:'blue'});
var c2 = s.circle(100,170,10).attr({fill:'red'});
var g = s.g(c1, c2);

g.transform('s2');

c1.drag(move, start );

Any idea where i'm wrong ?

Upvotes: 0

Views: 99

Answers (1)

Ian
Ian

Reputation: 13842

The problem will be that the example provided doesn't take into account the difference in transforms from the mouse coordinates to the element.

So to adapt to this, you will need to transform the dx,dy inversely, as when you drag for example 10px, you only want it to move 5px, as a simplified example.

I've done a couple of examples in the past here (try this first) and here (especially if you may have more complex nested transforms its worth looking here)

Here's the code in case the links don't work some time, its a plugin, so you can just call altDrag() instead of drag()

Snap.plugin( function( Snap, Element, Paper, global ) {

Element.prototype.altDrag = function() {
    this.drag( dragMove, dragStart, dragEnd );
    return this;
}

var dragStart = function ( x,y,ev ) {
        this.data('ot', this.transform().local );
}


var dragMove = function(dx, dy, ev, x, y) {
        var tdx, tdy;
        var snapInvMatrix = this.transform().diffMatrix.invert();
        snapInvMatrix.e = snapInvMatrix.f = 0;
        tdx = snapInvMatrix.x( dx,dy ); tdy = snapInvMatrix.y( dx,dy );
        this.transform( "t" + [ tdx, tdy ] + this.data('ot')  );

}

var dragEnd = function() {
}

Upvotes: 1

Related Questions