echarts怎么画二叉树
时间: 2023-10-25 13:39:07 浏览: 164
ECharts是一款基于JavaScript的可视化库,本身并不支持二叉树的绘制,但我们可以通过一些技巧来实现二叉树的绘制。
以下是示例代码,实现了一个简单的二叉树的绘制,供参考:
HTML代码:
```html
<div id="chart" style="width: 600px;height: 400px;"></div>
```
JavaScript代码:
```javascript
// 构造二叉树节点
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
// 计算二叉树节点的层级和位置
function calcTreeNodePos(node, level, left, right, posMap) {
if (!node) {
return;
}
var center = (left + right) / 2;
var pos = [center, level * 100];
posMap[node.val] = pos;
calcTreeNodePos(node.left, level + 1, left, center, posMap);
calcTreeNodePos(node.right, level + 1, center, right, posMap);
}
// 绘制二叉树
function drawTree(root) {
var dom = document.getElementById('chart');
var chart = echarts.init(dom);
var posMap = {};
calcTreeNodePos(root, 1, 0, 1, posMap);
var option = {
tooltip: {
show: false
},
series: [{
type: 'graph',
layout: 'none',
symbolSize: 50,
roam: false,
label: {
show: true
},
edgeSymbol: ['none', 'arrow'],
edgeSymbolSize: [4, 10],
edgeLabel: {
fontSize: 20
},
data: Object.keys(posMap).map(function (key) {
return {
name: key,
x: posMap[key][0],
y: posMap[key][1]
};
}),
edges: root ? [{
source: root.val,
target: root.val,
label: {
normal: {
show: false
}
},
lineStyle: {
normal: {
color: '#333',
width: 2,
curveness: 0.3,
opacity: 0.5
}
}
}].concat(getEdges(root)) : []
}]
};
chart.setOption(option);
// 获取二叉树的边
function getEdges(node) {
if (!node) {
return [];
}
var edges = [];
if (node.left) {
edges.push({
source: node.val,
target: node.left.val,
label: {
normal: {
show: true,
formatter: 'left'
}
},
lineStyle: {
normal: {
color: '#333',
width: 2,
curveness: 0.3,
opacity: 0.5
}
}
});
edges = edges.concat(getEdges(node.left));
}
if (node.right) {
edges.push({
source: node.val,
target: node.right.val,
label: {
normal: {
show: true,
formatter: 'right'
}
},
lineStyle: {
normal: {
color: '#333',
width: 2,
curveness: 0.3,
opacity: 0.5
}
}
});
edges = edges.concat(getEdges(node.right));
}
return edges;
}
}
// 示例二叉树
var root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);
// 绘制二叉树
drawTree(root);
```
运行代码,会得到一个如下图所示的二叉树:
![echarts_binary_tree.png](https://cdn.jsdelivr.net/gh/krislinzhao/CDN/blog/echarts_binary_tree.png)
阅读全文