【问题标题】:selecting multiple svg elements and dragging them in Raphael.js选择多个 svg 元素并在 Raphael.js 中拖动它们
【发布时间】:2011-04-30 22:07:00
【问题描述】:

有谁知道我如何做到这一点?

我基本上有一个包含多个形状、线条、文本等的 svg 文档……我正在尝试实现一个选择工具,它可以帮助我选择多个元素,将它们分组并拖动它们。

【问题讨论】:

    标签: svg selection raphael drag


    【解决方案1】:

    raphäel 中有一个特性叫做 set:http://raphaeljs.com/reference.html#set

    您可以将要拖动的所有元素添加到新集合中,然后将拖动机制应用到集合中。

    我给你做了这个:http://jsfiddle.net/Wrajf/

    这并不完美。我会将 mousemove 事件添加到文档中,但为此您需要一个像 jQuery 这样的库。否则,如果您将鼠标移动得快,您就会摔倒。

    【讨论】:

    • 我感觉到你了,猴子。为这个答案付出了如此多的努力,却发现它被提问者忽视了。
    【解决方案2】:

    我这样做了(example here):

    编辑:更干净的东西

    1. 创建方法来设置和检索元素组:

      Raphael.el.setGroup = function (group) {
        this.group = group;
      };
      Raphael.el.getGroup = function () {
        return this.group;
      };
      
    2. 创建分组元素的方法:

      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. 创建函数来拖动分组元素:

      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. 初始化 SVG 纸并创建你的元素(元素的顺序很重要)::

      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);
      
      };
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-06
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多