Selecting multiple svg elements and dragging them into Raphael.js

Does anyone know how I can achieve this?

I basically have an svg document with several forms, lines, text, etc ... and I'm trying to implement a selection tool that helps me select multiple elements, group them and drag them.

+7
source share
2 answers

RaphΓ€el has a function called set: http://raphaeljs.com/reference.html#set

You can add all the elements you want to drag to a new set, and then apply the drag and drop mechanism to the set.

I did this for you: http://jsfiddle.net/Wrajf/

This is not perfect. I would add the mousemove event to the document, but for this you need a library like jQuery. Otherwise, if you move the mouse to speed up, you will drop out.

+27
source

I did this ( example here ):

EDIT: something cleaner

  • Create methods to set and retrieve an element group:

    Raphael.el.setGroup = function (group) { this.group = group; }; Raphael.el.getGroup = function () { return this.group; }; 
  • Create a grouped items method:

     Raphael.fn.superRect = function (x, y, w, h, text) { var background = this.rect(x, y, w, h).attr({ fill: "#FFF", stroke: "#000", "stroke-width": 1 }); var label = this.text(x+w/2,y+h/2, text); var layer = this.rect(x, y, w, h).attr({ fill: "#FFF", "fill-opacity": 0, "stroke-opacity": 0, cursor: "move" }); var group = this.set(); group.push(background, label, layer); layer.setGroup(group); return layer; }; 
  • Create functions for dragging grouped items:

     var dragger = function () { this.group = this.getGroup(); this.previousDx = 0; this.previousDy = 0; }, move = function (dx, dy) { var txGroup = dx-this.previousDx; var tyGroup = dy-this.previousDy; this.group.translate(txGroup,tyGroup); this.previousDx = dx; this.previousDy = dy; }, up = function () {}; 
  • Initiate SVG paper and create your own elements (the order of the elements is important) ::

     window.onload = function() { var paper = Raphael(0, 0,"100%", "100%"); var x=50, y=50, w=30, h=20; paper.superRect(x, y, w, h, "abc").drag(move, dragger, up); x +=100; paper.superRect(x, y, w, h, "def").drag(move, dragger, up); }; 
+3
source

All Articles