开发者

selecting multiple svg elements and dragging them in Raphael.js

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.


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.


I did this (example here) :

EDIT : something cleaner

  1. 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;
    };
    
  2. 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;
    };
    
  3. 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 () {};
    
  4. 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);
    
    };
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜