Erel Segal-Halevi
Erel Segal-Halevi

Reputation: 36823

Dragging a circle

I am beginning to use snap.svg, and stuck in a probably simple question. I draw a circle, and want to let the user drag it around, and when the user stops dragging, I want to know the alert the final position of the circle.

I started with this:

var s = Snap("#svg");
var d = s.circle(20,20,5);

Then I created the following functions as drag event-handlers; I only need the drag-end event so I made the two other event-handlers null:

var endFnc = function(e) { 
    alert("end: "+e.layerX+","+e.layerY); 
}

var startFnc = null;

var moveFnc = null;

Then I installed the drag event handlers:

d.drag(moveFnc,startFnc,endFnc);

Whenever I tried to drag a circle, the end event fired, but, the circle did not move.

So I figured maybe I have to also create the drag move event (although I don't need it):

var moveFnc = function(dx, dy, x, y) {
  this.transform('t' + x + ',' + y);
}

Now the circle did move, but, not exactly at the mouse, but approximately 20 pixels at its bottom right.

I read the documentation here: http://snapsvg.io/docs and there seems to be no explanation about how to create working drag events.

How does anyone get this knowledge?!

Upvotes: 0

Views: 537

Answers (1)

Erel Segal-Halevi
Erel Segal-Halevi

Reputation: 36823

After struggling for some hours to do this with snap.js, I finally discovered svg.js and its draggable plugin, with which it is so much easier:

var draw = SVG('svg');
var circle = draw.circle(10).attr({cx:30,cy:30,fill:'#f06'});
circle.dragend = function(delta, event) {
    alert(this.attr('cx'))
}
circle.draggable();

So, I switched to svg.js ...

Upvotes: 1

Related Questions