Thursday, 21 May 2015

SVG with RaphaelJS - Drag and Drop in RaphaelJS


Welcome to this section of the weekly series SVG with RaphaelJS.

The drag and drop functionality in RaphaelJS enables us to move elements from one location to another on the RaphaelJS paper.

The documentation is relatively straightforward on how to do this so an example will suffice. We start off by drawing a circle at x = 100 and y = 250 with the radius of 50. The code to do this is given below:

var circle = paper.circle(100, 250, 50).attr({ 'fill' : 'red', 'stroke-width' : 5 });

Notice that we give the circle a fill of red and a stroke-width of 5. This is shown below:


Next we write our dragstart, dragmove and dragend functions and assign them to our circle element.

Our final code is shown below.

$(function(){ var paper = Raphael('container', 500, 500);
// Draw a circle at the left hand side of the viewport
var circle = paper.circle(100, 250, 50).attr({ 'fill' : 'red', 'stroke-width' : 5 });
circle.drag(dragmove, dragstart, dragend);
function dragstart(x, y, e){
this.current_transform = this.transform();
this.attr("fill", "yellow");
}
function dragmove(dx, dy, x, y, e){
this.transform(this.current_transform+'T'+dx+','+dy)
}
function dragend(e){
this.current_transform = this.transform();
this.attr("fill", "red");
}
});

Note that in the dragstart method when we start dragging the circle, we change its fill colour to yellow.

We also get its current transform first before motion starts. This is because when motion starts, we want to move it in consideration of the transform that it had before motion.

In the dragmove function, we change the transform of the circle in consideration of how it has moved in the x and y directions. The variables dx and dy mean the difference in the motion of the circle along the x and y directions.

You can view the code for this on my dropbox or download the GitHub repository.

No comments:

Post a Comment