2014-05-16 32 views
0

以下代码的目的是拖动两个矩形中的任意一个,并保持它们与线条连接。但是,正如您在jsfiddle中看到的,该线路在其他地方移动。这段代码有什么问题?Raphael:在保持连接状态下拖动矩形

这是HTML

<div id="canvas"></div> 

这是JavaScript

window.onload = function() { 

    var paper = Raphael("canvas", 600, 600); 
    var rect1 = paper.rect(100, 100, 100, 100).attr({"fill":"blue"}); 
    var rect2 = paper.rect(400, 100, 100, 100).attr({"fill":"green"}); 

    rect1.node.id = "rect1"; 
    rect2.node.id = "rect2"; 

    var x1=200, y1=150, x2=400, y2=150; 
    var line = paper.path(['M', x1, y1, 'L', x2, y2]); 

    var start = function() { 
     // storing original coordinates 
     this.ox = this.attr("x"); 
     this.oy = this.attr("y"); 
    }, 
    move = function (dx, dy) { 
     // move will be called with dx and dy 
     this.attr({x: this.ox + dx, y: this.oy + dy}); 

     if (this.node.id == "rect1") { 
      x1 += dx; 
      y1 += dy; 
     } 
     else if (this.node.id == "rect2") { 
      x2 += dx; 
      y2 += dy; 
     } 
     line.attr("path", ['M', x1, y1, 'L', x2, y2]); 
    }, 
    up = function() { 
     // restoring state 
}; 


rect1.drag(move, start, up); 
rect2.drag(move, start, up); 

    };  

回答

2

好,

可以使用获得的平方边框

Element.getBBox();

方法和计算从

 if (this.node.id == "rect1") { 
      var bb=rect1.getBBox(); 
      x1=bb.x2; 
      y1=bb.y+(bb.height/2); 
     } 
     else if (this.node.id == "rect2") { 
      var bb2=rect2.getBBox(); 
      x2=bb2.x; 
      y2=bb2.y+(bb2.height/2); 
     } 

小提琴的路径值: http://jsfiddle.net/wrJKm/2/

0

编辑:原也不太工作的时候都被感动了,我更新为使用this.ox这.oy属性,这些属性都是非常有用的。小提琴也完全更新。

dx和dy是从初始位置开始的相对位置,否则它们的值始终在-1到1的范围内以指示它每次移动。这意味着您的原始x1,y1等等会越来越远地移动。相反,你应该保持原始的位置不变,只是由DX,DY对其进行修改:

http://jsfiddle.net/tQ9av/2/

if (this.node.id == "rect1") { 
    n_x1 = this.ox + dx + 100; 
    n_y1 = this.oy + dy + 50; 
} 
else if (this.node.id == "rect2") { 
    n_x2 = this.ox + dx; 
    n_y2 = this.oy + dy + 50; 
} 
line.attr("path", ['M', n_x1, n_y1, 'L', n_x2, n_y2]); 
+0

抱歉,您的jsfiddle不工作,是编辑后的版本? – ps0604

+0

我没有更新网址 - 应该这样做。 –

+0

谢谢,你的答案也适用 – ps0604

相关问题