var cy = cytoscape({ container: document.getElementById('graph'), ready: function () { console.log('ready'); }, style: cytoscape.stylesheet() .selector('node') .css({ 'content': 'data(label)', 'text-valign': 'center', 'text-halign': 'center', 'width': '80px', 'shape': 'roundrectangle' }) .selector(':selected') .css({ 'border-width': 5, 'border-color': '#337ab7', 'transition-property': 'background-color, line-color, target-arrow-color', 'transition-duration': '0.4s' }) .selector('edge') .css({ 'target-arrow-shape': 'triangle', 'width': 10, 'line-color': '#337ab7', 'target-arrow-color': '#337ab7' }) }); // Deletes a node $("#deleteNode").click(function () { if (cy.$(":selected").length > 0) { cy.$(":selected").remove(); } }); // Adds a node (linked if a parent has been selected first $("#addNode").click(function () { var newnodeid = (Date.now()).toString(); var newedgeid = (Date.now() + 1).toString(); console.log(newnodeid); console.log(newedgeid); var addNode = cy.add({ group: "nodes", data: { id: newnodeid, label: $("#nodeName").val(), name: $("#nodeName").val(), type: 'node' }, position: { x: 100, y: 100 } }); if (cy.$(":selected").length > 0) { var parentId = cy.$(":selected").data("id"); var addEdge = cy.add({ group: "edges", data: { id: newedgeid, source: parentId, target: newnodeid, type: 'edge' } }); } }); $("#centerGraph").click(function () { cy.fit(); });
<script src="http://cytoscape.github.io/cytoscape.js/api/cytoscape.js-latest/cytoscape.min.js"></script> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Graph Demo Script</h3> </div> <div class="panel-body"> <ul> <li>type a label</li> <li>click "add node"</li> <li>select the node</li> <li>type a new label</li> <li>click "add node"</li> </ul> </div> </div> <input type="text" id="nodeName" /> <button id="addNode" class="btn btn-success"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> ADD NODE</button> <button id="deleteNode" class="btn btn-danger"><span class="glyphicon glyphicon-minus" aria-hidden="true"></span> DELETE NODE</button> <button id="centerGraph" class="btn btn-default"><span class="glyphicon glyphicon-resize-full" aria-hidden="true"></span> FIT NODES</button> <div id="graph" />
#graph { border: dashed 3px #000; border-radius: 5px; margin: 5%; width: 90%; height: 300px; }