如何在JointJS中交互式地创建链接

How to interactively create links in JointJS

本文关键字:创建 链接 交互式 JointJS      更新时间:2023-09-26

我想以交互方式添加链接到我的基于JointJS的图形。

我的想法是在pointerdown上创建一个小的临时节点,从原始节点到这个临时节点的链接,将它拖到另一个节点的顶部,并在pointerup上创建真正的链接,删除临时链接和节点。

不幸的是,我不知道如何说服指针移动临时元素,而不是pointerdown事件发生的节点。任何想法?谢谢!

var tmp_obj;
paper.on('cell:pointerdown', function(cellView, evt, x, y) {
    if(evt.button == 1) {
        // Freeze the selected node so it does not move
        paper.findViewByModel(cellView.model).options.interactive = false;
        // Create a small temporary node on top of the selected node
        tmp_obj = new joint.shapes.basic.Rect({
            position: { x: x, y: y },
            size: { width: 5, height: 5 }
        }
        // Create the link between the original node and the small temporary node
        // And now?
    }
}
paper.on('cell:pointerup', function(cellView, evt, x, y) {
    if(evt.button == 1) {
        // Unfreeze the origin node
        paper.findViewByModel(cellView.model).options.interactive = true;
        // Delete the temporary object (and temporary link)
        tmp_obj.remove()
        // Find the first element below that is not a link nor the dragged element itself.
        var elementBelow = graph.get('cells').find(function(cell) {
            if (cell instanceof joint.dia.Link) return false; // Not interested in links.
            if (cell.id === cellView.model.id) return false; // The same element as the dropped one.
            if (cell.getBBox().containsPoint(g.point(x, y))) {
                return true;
            }
            return false;
        });
        // create the link from cellView to elementBelow 
    }
});

也许你可以使用JointJS的磁铁特性?如果在JointJS元素的SVG子元素上设置magnet: true,则该元素将变为活动元素,并允许用户从该元素开始创建链接。例如:

var r = new joint.shapes.basic.Rect({
    position: { x: 50, y: 50 },
    size: { width: 100, height: 40 },
    attrs: { text: { text: 'basic.Rect', magnet: true } }
});

这将使元素表现得像一个端口。

防止悬垂链接:

joint.dia.Paper({ linkPinning: false })

这是一个很好的解决方案。

可以组合

linkView.startArrowheadMove('target');

evt.data.view.pointermove(evt, p.x, p.y);