gojs+dagre实现自动布局流程图效果代码
代码语言:html
所属分类:图表
代码描述:gojs+dagre实现自动布局流程图效果代码,设置了右键菜单,可以删除和克隆节点。
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body onload="init()"> <div id="sample"> <button onclick="autolayout()">auto layout</button> <button onclick="duplicateNode()">duplicateNode</button> <p>right click for context menu</p> <div id="myDiagram" style="background-color: whitesmoke; border: solid 1px black; width: 100%; height: 400px"></div> </div> <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/go.js"></script> <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/dagre.min.js"></script> <script> var nodes, links, myModel, $, myDiagram; function generateNodeDataArray() { var nodeDataArray = []; for (n in nodes) { var nodeData = { key: n, label: nodes[n].label }; if (nodes[n].x && nodes[n].y) { nodeData.location = new go.Point(nodes[n].x, nodes[n].y); }; nodeDataArray.push(nodeData); } return nodeDataArray; } function autolayout() { console.log(JSON.stringify(myModel)); // Create a new dagre graph , note: this graph is only used for layout. var dagreGraph = new dagre.graphlib.Graph(); dagreGraph.setGraph({ rankdir: 'LR', nodesep: 100, ranksep: 20, edgesep: 20 }); // Default to assigning a new object as a label for each new edge. dagreGraph.setDefaultEdgeLabel(function () {return { label: 'label' };}); for (n in nodes) { dagreGraph.setNode(n, { width: nodes[n].width, height: nodes[n].height }); }; links.forEach(function (link) { dagreGraph.setEdge(link.from, link.to, { minlen: 2 }); }); dagre.layout(dagreGraph); dagreGraph.nodes().forEach(function (v) { var node = dagreGraph.node(v); console.log("Node " + v + ": " + JSON.stringify(node)); // myModel.nodeDataArray[n.id].loc = n.x+' '+n.y; nodes[v].x = node.x; nodes[v].y = node.y; }); reloadDiagram(); } function duplicateNode() { if (myDiagram.selection.size !== 1) { alert("Please select one state"); return; } var selectedState = myDiagram.selection.first(); var oldState = selectedState.data.key; var newState = oldState + '1'; nodes[newState] = { label: 'new state' }; links.push({ from: oldState, to: newState }); reloadDiagram(); } function deleteNode() { var selectedState = myDiagram.selection.first(); delete nodes[selectedState.data.key]; reloadDiagram(); } function reloadDiagram() { // initialize data model myModel = $(go.GraphLinksModel); myModel.nodeDataArray = generateNodeDataArray(); .........完整代码请登录后点击上方下载按钮下载查看
网友评论0