vis.js 中的自定义边绘制功能

Custom edge drawing function in vis.js

我正在使用 vis.js 库绘制网络,但我需要自定义绘制边的方式。例如,我想用红色绘制 50% 的边缘,用蓝色绘制另外 50% 的边缘。

有办法吗?

您不能直接自定义边的一部分,但可以使用充当连接器的虚拟不可见节点来创建两条不同的边(每条边都有自己的样式)。由于虚拟节点是不可见的,因此两条边看起来像是同一边的两个部分。

例如,假设您想用半绿半红边连接两个节点:

var nodes = new vis.DataSet([
    {id: 1, label: '1'},
    {id: 2, label: '2'},
    {id: 'dummy', hidden: true}
]);

var edges = new vis.DataSet([
    {from: 1, to: 'dummy', color:'red'},
    {from: 'dummy', to: 2, color:'green'}
]);

var graph = {nodes: nodes, edges: edges};

终于找到方法了:

var nodes = new vis.DataSet
([
    {id: 1, label: '1'},
    {id: 2, label: '2'},
]);

var edges = new vis.DataSet
([
    {from: 1, to: 2, color:'red'},
]);

var graph = {nodes: nodes, edges: edges};
var network = new vis.Network(container, graph, options);
var percent = 50;
network.on("afterDrawing", function (ctx)
{
    var pos = network.getPositions([1, 2]);
    ctx.strokeStyle = ctx.filStyle = 'green';
    ctx.moveTo(pos[1].x, pos[1].y);
    ctx.lineTo(pos[1].x + (pos[2].x-pos[1].x)*percent/100, pos[1].y + (pos[2].y - pos[1].y)*percent/100);
    ctx.fill();
    ctx.stroke();
});