JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>mxGraph sample</title>
<script type="text/javascript">
const mxLoadResources = false
const mxLoadStylesheets = false
</script>
<script type="text/javascript" src="https://www.unpkg.com/mxgraph/javascript/mxClient.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://www.unpkg.com/mxgraph/javascript/src/css/common.css">
</head>
<body>
<div id='export-button'></div>
<div id="container"></div>
</body>
</html>
JavaScript
// グラフを表示する領域を確保
const container = document.getElementById('container')
// グラフのインスタンス生成
const graph = new mxGraph(container)
// グラフにノードやエッジを追加する際に必要
const parent = graph.getDefaultParent()
// 今回は階層グラフを自動レイアウトで描画したいため、レイアウトのインスタンスを生成
const layout = new mxHierarchicalLayout(graph)
// tooltipを有効にします
graph.setTooltips(true)
// tooltipで表示させたい内容を設定します
graph.getTooltipForCell = cell => {
if (graph.getModel().isEdge(cell)) {
const srcNodeLabel = cell.source.getValue()
const dstNodeLabel = cell.target.getValue()
return `this edge is directed from node ${srcNodeLabel} to node ${dstNodeLabel}`
} else {
const nodeLabel = cell.getValue()
return `node ${nodeLabel}`
}
}
// クリックしたノードをオレンジ色に変更します
graph.addListener('click', (sender, evt) => {
const cell = evt.getProperty('cell')
if (graph.getModel().isVertex(cell)) {
graph.setCellStyles('fillColor', 'orange', [cell])
}
})
// グラフをexportするためのボタンを配置します
const button = document.createElement('button');
mxUtils.write(button, 'export')
mxEvent.addListener(button, 'click', () => {
exportGraph()
})
document.getElementById('export-button').appendChild(button)
function exportGraph() {
const svg = createSvg()
const blob = new Blob([svg], {
'type': 'svg/plain'
})
const link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = 'graph.svg'
link.click()
}
function createSvg() {
const scale = 1
const border = 1
const vs = graph.getView().scale
const bounds = graph.getGraphBounds()
// SVGのルート要素を作る
const root = mxUtils.createXmlDocument().createElementNS(mxConstants.NS_SVG, 'svg')
root.setAttribute('xmlns', mxConstants.NS_SVG)
root.setAttribute('xmlns:xlink', mxConstants.NS_XLINK)
root.setAttribute('width', `${Math.ceil(bounds.width * scale / vs) + 2}px`)
root.setAttribute('height', `${Math.ceil(bounds.height * scale / vs) + 2}px`)
root.setAttribute('version', '1.1')
// グラフを記述
const svgCanvas = new mxSvgCanvas2D(root)
...