我想我以前的答案仍然可行,但這是我在項目中實現它的方式。它比其他答案更有優勢,因爲它不要求您使用自定義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) }
});
完美!感謝您的更新答案! – dalvacoder
如果它適合你,你能不接受我以前的答案?我認爲如果未來人們看到這個問題會首先看到第二個答案,那會更好:) –