2014-05-16 34 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

相關問題