Akshay
Akshay

Reputation: 14368

Snap drag position gets back to normal when dragged second time

I am trying to make a curvy slider where one can click and drag a circle along a path. That is working fine but when i drag the circle after it has been dragged to certain position, it gets back to it's original position

var s=Snap('svg');
animateAlongPath = function (path, element) {
 var len = Snap.path.getTotalLength(path);
    var move = function(dx) {
        var movePoint=Snap.path.getPointAtLength(path, dx);
        this.attr({ cx: movePoint.x, cy: movePoint.y });
}


element.drag(move)
}  
var path=s.path('M10 200 q 120 -120 140 0 t 140 0').attr({
    fill:'none',
    stroke:'black'
});
var circle=s.circle(10,200,5);
animateAlongPath(path,circle)
<script src="https://cdnjs.cloudflare.com/ajax/libs/snap.svg/0.3.0/snap.svg-min.js"></script>
<svg width="500" height="500" ></svg>

Example image

enter image description here

Upvotes: 1

Views: 74

Answers (1)

Ian
Ian

Reputation: 13852

To answer that specific question, its because you are using 'dx' instead of 'x' on the drag. So 'dx' (the difference from the start of the drag) will naturally get reset each time.

So instead for the move function, you need to use the x parameter, eg

var move = function( dx, dy, x, y ) {
    var movePoint=Snap.path.getPointAtLength(path, x);
    this.attr({ cx: movePoint.x, cy: movePoint.y });
}

jsfiddle

However, you quite possibly don't want to end up with this, as you note it doesn't always match up.

I assume this is because 'x' or 'dx' accross the screen, doesn't translate across a curved line (due to using the curved lines length), it would only work on a straight line.

Thats beyond the scope of this question, but I have answered similar which may help at SO question on dragging along line especially if you look at the gradsearch func (I didn't come up with that, I think it was in the original question).

Upvotes: 1

Related Questions