matthew ephraim

Draggability for the Raphaël Library

I’ve been using the Raphaël JavaScript library a lot lately for a JavaScript SVG project I’ve been working on. It’s easy to use and eases a lot of the pain of using JavaScript with SVG. However, I eventually came to a point where I needed to have SVG elements that could be dragged around on the Raphael canvas. After looking around for a good plugin that would allow me to do what I wanted, I decided that I needed to write my own. The result is the raphael.draggable plugin.

raphael.draggable is fairly straightforward to use. You simply need to call the draggable.enable() on the raphael object you would like to enable the plugin for. raphael.draggable works for all raphael elements and for raphael sets as well. Sets that have raphael.draggable enabled will drag all elements in the set whenever any element in the set is dragged.

Using the raphael.draggable plugin

 // Creating a canvas and enabling draggable for it
var paper = Raphael(0,0, 800, 600);
paper.draggable.enable();

// Creating a rectangle element and enabling draggable for it
var rect = paper.rect(0, 0, 100, 100);
rect.attr({ 'fill': 'white' });
rect.draggable.enable();

// Creating a set and enabling draggable for it
var set = paper.set();
set.draggable.enable();
set.push(rect);

Currently, raphael.draggable has only been tested for Firefox and Safari. Those are the only two browsers I needed to test it for. Source code and documentation are available on github. Constructive criticism, and especially constructive contributions to the code are welcome!

Tags:

2 Responses to “Draggability for the Raphaël Library”

  1. Alex Says:

    This sounds awesome, and just the thing I was looking for. Does this mean that you have some x,y attributes you can modify as well, and the group of objects have their coordinates changed according to their various distances from eachother, or is it more like a grouping of the draggable events (which then triggers coordinate changes in a cascading fashion)?

    Btw, I know I’m late to this post, and not sure if anything has changed since it was posted. I’m interested in doing more Raphael stuff, but find plugins and such hard to find.

  2. Matthew Ephraim Says:

    @Alex

    The set object in Raphael already has a translate method that will move the entire set in an x and y direction. I’m not sure if that’s what you were looking for.

    My draggable plugin takes advantage of that method to move the entire set when you click and drag any of the elements inside of the set.

    I’m still working on the plugin, and I have some additional changes that I’m hoping to push once they get fleshed out a little bit more.

Leave a Reply