如何保持jointjs细胞不会溢出纸张?

我正在使用jointjs制作用户可编辑的图表。 用户可以拖动它们并重新定位每个单元格。 但是,当一个单元被拖到边缘时,它会溢出并被切断。 我希望防止这种情况发生,而不是单元格在到达纸张边缘之前停止而不允许越过边缘,因此总是完全保留在纸张内。 这个行为可以在jointjs自己的演示中看到:

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

尝试将单元格拖动到边缘,您将看到它最终在穿过纸张元素的边缘时变得隐藏。

其次,我使用插件进行有向图布局,在这里找到:

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

如您所见,只要您的点击布局,树位置就会自动移动到纸张元素的左上角。 如何修改这些默认位置? 我看到的所提供函数的唯一选项是行之间的空间和节点之间的空间,没有初始位置。 假设我想要在点击“布局”时出现在纸张中间的树,我将在哪里进行更改? 在此先感谢您的帮助。

我认为我以前的答案仍然可行,但这就是我在项目中实现的方法。 它优于其他答案,因为它不需要你使用自定义的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) } }); 

作为Roman答案的补充, restrictTranslate也可以配置为true以限制元素移动到纸张区域的边界。

例:

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

I.为防止元素溢出纸张,您可以使用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

编辑:我认为这种方法仍然可行,但我现在认为我的另一个答案更简单/更好。

JointJS docs提供了一个样本,其中形状的运动与椭圆形相对应:

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

它的工作原理

  1. 为元素定义新视图,扩展joint.dia.ElementView
  2. 覆盖视图中的pointerdownpointermove事件以实现约束。 这是通过基于鼠标位置和约束计算新位置,然后将其传递给基本ElementView事件处理程序来完成的
  3. 强制paper使用您的自定义元素视图

这种方法可以很容易地适应,以防止形状被拖离纸张的边缘。 在步骤2中,您将使用Math.min()Math.max()来计算新位置,而不是像教程中那样计算椭圆的交点。