Search code examples
javascriptvis.js-networkvis.js

Custom edge drawing function in vis.js


I'm using the vis.js library to draw a network but I need to customize the way the edges are drawn. For example, I would like to draw let's say 50% of the edge in red and the other 50% in blue.

Is there a way to do this?


Solution

  • Finally found a way to do it:

    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();
    });