Reputation: 179
Does anyone know how I can achieve this?
I basically have an svg document with multiple shapes,lines,text,etc... and I am trying to implement a selection tool which helps me select multiple elements, group them and drag them.
Upvotes: 7
Views: 10020
Reputation: 61
I did this (example here) :
EDIT : something cleaner
Create methods to set and retrieve the group of an element :
Raphael.el.setGroup = function (group) {
this.group = group;
};
Raphael.el.getGroup = function () {
return this.group;
};
Create the method of your grouped elements :
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 to drag a grouped elements :
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 () {};
Init SVG paper and create your elements (the order of element 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);
};
Upvotes: 3
Reputation:
There is a feature in raphäel called set: http://raphaeljs.com/reference.html#set
You can add all the elements you want to drag around to a new set and then apply the dragging mechanism to the set.
I made you this: http://jsfiddle.net/Wrajf/
It's not perfect. I would add the mousemove event to the document, but for that you need a library like jQuery. Otherwise if you move the mouse to fast you have a fall out.
Upvotes: 27