无法拖动元素集

时间:2014-01-21 06:55:05

标签: svg raphael

我正在使用路径(Raphael和SVG)创建两个元素(1.箭头形状和2.虚线),我想将这两个元素拖动到一起,但我只能将它们单独拖动。这是我的代码:

 gaugeSvg = Raphael("gauge");

 $(document).ready( function () {
            redraw();
       });

 function redraw() {

        //Add a Arrow and line
        var rect = gaugeSvg.path('M 0 0 L 40 -34 L 40 -14 L 80 -14 L 80 14 L 40 14 L 40 34 Z');

        rect.attr({
        "stroke": "black",
        "fill" : "black",
        "enable" : "true",
        }).translate(left + width, goalY);

        var txt =  gaugeSvg.path('M 0 0 L ' + width + " 0");

        txt.attr({
        "stroke": "black",
        "stroke-width": 12,
        "stroke-dasharray": "-",
        "stroke-linecap": "round"
        }).translate(left, goalY);

        //Create a set so we can move the
       //arrow and line at the same time
       var g = gaugeSvg.set();
       g.push(rect, txt);
      // var g = gaugeSvg.set(rect, txt);

       var me = this,
       lx = 0,
       ly = 0,
       ox = 0,
       oy = 0,
       moveFnc = function(dx, dy) {
           this.translate(dx-ox, dy-oy);
           ox = dx;
           oy = dy;  
       },
       startFnc = function() {},
       endFnc = function() {
           ox = lx;
           oy = ly;
       };

        g.drag(moveFnc, startFnc, endFnc);
     }

1 个答案:

答案 0 :(得分:0)

我没有使用过Rapheal。但是我用SVG和Javascript实现了这个Drag功能。

要移动多个元素,您需要对它们进行分组。意味着将这些元素放在'g'组中,然后在这个'g'上应用拖动功能。一旦完成,你需要“取消组合”它们。

你可以在这里看到演示http://jsfiddle.net/rehankhalid/5t5pX/

var mainsvg = document.getElementsByTagName('svg')[0];

 function mousemove(event) {
        var svgXY = getSvgCordinates(event);// get current x,y w.r.t to your svg.
        dx = svgXY.x - mx;// mx means x cordinates of mouse down
        dy = svgXY.y - my;

        draggroup.setAttribute('transform', 'translate(' + dx + ',' + dy + ')');

    }

function getSvgCordinates(event) {
            var m = mainsvg.getScreenCTM();
            var p = mainsvg.createSVGPoint();
            var x, y;

            x = event.pageX;
            y = event.pageY;

            p.x = x;
            p.y = y;
            p = p.matrixTransform(m.inverse());

            x = p.x;
            y = p.y;

            x = parseFloat(x.toFixed(3));
            y = parseFloat(y.toFixed(3));

            return {x: x, y: y};
        }