cytoscape.jscytoscape-web

Adding extra information above the node in cytoscape.js


Using cytoscape.js to draw a graph. I need to add circle above the node at top-right position. After drawing the graph, is there any API wherein we can get positions of nodes.

Also, I have used the code as follows: elements : { nodes : [ { data : { id : '1', name : 'A' } } ] }

var pos = cy.nodes("#1").position();

'#1' is the ID of the node in the data attribute. However, we are not able to add the node/circle at that exact position.


Solution

  • If you want to get something like:

    enter image description here

    then this code adds the circle to a node knowing it's id:

    function addCircle(nodeId, circleText){
        var parentNode = cy.$('#' + nodeId);
        if (parentNode.data('isCircle') || parentNode.data('circleId'))
            return;
        parentNode.lock();
        var px = parentNode.position('x') + 10;
        var py = parentNode.position('y') - 10;    
        var circleId = (cy.nodes().size() + 1).toString();
        parentNode.data('circleId', circleId);
        cy.add({
            group: 'nodes',
            data: { weight: 75, id: circleId, name: circleText, isCircle: true },
            position: { x: px, y: py },
            locked: true
        }).css({
            'background-color': 'yellow',
            'shape': 'ellipse',
            'background-opacity': 0.5
        }).unselectify();
    }
    
    // ...
    
    addCircle('1', 'Bubble A');
    

    but it must be called after the node's positions are known, when the layout settles down.

    The locking is there to prevent that node and it's circle get apart.

    jsFiddle demo: http://jsfiddle.net/xmojmr/wvznb9pf/

    Using compound node which would keep the node and it's circle together would be probably better, once the support for positioning child nodes is implemented.

    Disclaimer: I'm cytoscape.js newbie, use at your own risk