2015-05-05 71 views
11

我正在使用jointjs來製作用戶可編輯的圖表。用戶可以拖動它們並重新定位每個單元格。然而,當一個單元被拖到邊緣時,它會溢出並被切斷。我想防止這種情況發生,而不是單元在到達紙張邊緣之前停止,並且不允許它穿過邊緣,因此始終完全停留在紙張內。該行爲可以看出,在這裏jointjs'自己的演示:如何避免jointjs細胞溢出紙張?

http://www.jointjs.com/tutorial/ports

嘗試拖動單元格的邊緣,你會看到它,因爲它穿過紙件的邊緣最終被隱藏起來。

其次,我使用的插件有向圖的佈局,在這裏找到:

http://jointjs.com/rappid/docs/layout/directedGraph

正如你所看到的,在樹中的位置自動移動到紙質濾芯,只要您點擊左上角佈局。我如何修改這些默認位置?我看到的提供的功能的唯一選項是行列之間的空間和節點之間的空間,沒有初始位置。假設我想點擊「佈局」讓樹出現在紙的中間,那麼我需要在哪裏進行更改?預先感謝您的幫助。

回答

5

我想我以前的答案仍然可行,但這是我在項目中實現它的方式。它比其他答案更有優勢,因爲它不要求您使用自定義elementView,並且看起來更簡單(對我來說)。

(工作的jsfiddle:http://jsfiddle.net/pL68gs2m/2/

paper,處理cell:pointermove事件。在事件處理程序中,找出事件被觸發的邊界框cellView,並使用它來限制移動。

var graph = new joint.dia.Graph; 

var width = 400; 
var height = 400; 
var gridSize = 1; 

var paper = new joint.dia.Paper({ 
    el: $('#paper'), 
    width: width, 
    height: height, 
    model: graph, 
    gridSize: gridSize 
}); 

paper.on('cell:pointermove', function (cellView, evt, x, y) { 

    var bbox = cellView.getBBox(); 
    var constrained = false; 

    var constrainedX = x; 

    if (bbox.x <= 0) { constrainedX = x + gridSize; constrained = true } 
    if (bbox.x + bbox.width >= width) { constrainedX = x - gridSize; constrained = true } 

    var constrainedY = y; 

    if (bbox.y <= 0) { constrainedY = y + gridSize; constrained = true } 
    if (bbox.y + bbox.height >= height) { constrainedY = y - gridSize; constrained = true } 

    //if you fire the event all the time you get a stack overflow 
    if (constrained) { cellView.pointermove(evt, constrainedX, constrainedY) } 
}); 
+0

完美!感謝您的更新答案! – dalvacoder

+0

如果它適合你,你能不接受我以前的答案?我認爲如果未來人們看到這個問題會首先看到第二個答案,那會更好:) –

2

編輯:我認爲這種方法仍然可行,但我現在認爲我的其他答案更簡單/更好。

的JointJS文檔提供,其中的形狀的運動contrained躺在橢圓的樣品:

http://www.jointjs.com/tutorial/constraint-move-to-circle

它通過

  1. 定義爲您的元素的新視圖,擴展爲joint.dia.ElementView
  2. 包含pointerdownpointermove事件在視圖中實現的約束INT。這是通過計算一個新的位置,根據鼠標的位置和約束,然後通過這個到基ElementView事件處理
  3. 強制paper使用您的自定義元素視圖

這種方法可以做到很容易適應,以防止從紙張邊緣拖出形狀。在第2步中,您可以使用Math.min()Math.max()來計算新的位置,而不是像本教程中那樣計算與橢圓的交點。

+0

感謝,好像這是要走的路,雖然還不能確定如何計算,但不適保持與它搞亂。 – dalvacoder

+0

嗯。我的積壓項目上有一個項目可以做到這一點。這是相當低的,但我會看看如果我可以推它,然後在這裏發佈解決方案; o) –

+0

太棒了!謝謝! – dalvacoder

5

一可避免元素溢出您可以使用restrictTranslate紙張選項(JointJS v0.9.7 +)的文件。

paper.options.restrictTranslate = function(cellView) { 
    // move element inside the bounding box of the paper element only 
    return cellView.paper.getArea(); 
} 

http://jointjs.com/api#joint.dia.Paper:options

II。使用marginXmarginY DirectedGraph佈局選項移動結果圖的左上角,即向左側和頂部添加頁邊距。

http://jointjs.com/rappid/docs/layout/directedGraph#configuration

3

作爲除了羅馬的回答,也restrictTranslate可以被配置爲true限制到紙區域的邊界的元件的運動。

例子:

var paper = new joint.dia.Paper({ 
    el: $('#paper'), 
    width: 600, 
    height: 400, 
    model: graph, 
    restrictTranslate: true 
})