先放效果圖
代碼:
function init(set, data) { var $ = go.GraphObject.make; // for conciseness in defining templates myDiagram = $(go.Diagram, "goJs_container", // create a Diagram for the DIV HTML element { "undoManager.isEnabled": true, // enable undo & redo layout: $(go.TreeLayout) }); //新建節點 myDiagram.nodeTemplate = $(go.Node, "Auto", $(go.Shape, "RoundedRectangle", { fill: "white" },// Shape.fill is bound to Node.data.color new go.Binding("fill", "bgcolor")), // 設置節點的背景色 $(go.TextBlock, { margin: 8, font: "bold 15px sans-serif" }, // , stroke: '#ddd' Specify a margin to add some room around the text// TextBlock.text is bound to Node.data.key new go.Binding("text", "key"), new go.Binding("stroke", "color")) // 設置節點的前景色 ); // nodeTag // 新建線條和箭頭 myDiagram.linkTemplate = $(go.Link, $(go.Shape, // the link shape { strokeWidth: 2, stroke: 'white' }), $(go.Shape, // the arrowhead { toArrow: 'OpenTriangle', fill: null, stroke: 'white' }) ); // 其他設置,圖表在畫布中居左顯示 myDiagram.initialContentAlignment = go.Spot.Left; //通過節點數據和關系數組完成關系圖。 myDiagram.model = new go.GraphLinksModel(set, data); }
設置節點的背景色代碼解析:new go.Binding("fill","bgcolor") ,將nodeDataArray里面設置的bgcolor屬性綁定到“ fill ”屬性上;
設置節點的前景色代碼解析:new go.Binding("stroke","color") ,將nodeDataArray里面設置的color屬性綁定到“ stroke ”屬性上;
關於nodeDataArray數據結構格式(也就是我的代碼中的set數組)如下:
set.push(
{ key: '節點1', color: '#ddd', bgcolor: '#4d65a6' },
{ key: '節點2', color: '#333', bgcolor: '#b9b2b6' }
);