<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!-- 引入 ECharts 文件 -->
<script src="echarts.min.js"></script>
</head>
</html>
复制代码
我是在react项目中直接npm了echarts, 因此在入口文件直接按需加载须要使用的Graph图html
// 引入 ECharts 主模块
import echarts from 'echarts/lib/echarts';
// 引入思惟图
import 'echarts/lib/chart/graph';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
复制代码
1.为画布准备一个dom元素 设置宽高node
<body>
<!-- 为 ECharts 准备一个具有大小(宽高)的 DOM -->
<div id="main" style="width: 600px;height:400px;"></div>
</body>
复制代码
2.在js中获取dom元素,初始化画布react
var myChart = echarts.init(document.getElementById('main'));
复制代码
以后再经过echarts的setOpton填入数据便可。webpack
须要倒入的数据为两部分:web
后端传来的link值按格式引入,官方例子以下:npm
links: [{
source: '节点1',
target: '节点3'
}, {
source: '节点2',
target: '节点3'
}, {
source: '节点2',
target: '节点4'
}, {
source: '节点1',
target: '节点4'
}]
复制代码
将后端数据push进link集:后端
let links = [];
for(var i in data.relation){
links.push({
source : data.relation[i].source,
target : data.relation[i].target
});
}
复制代码
节点数据是须要给出节点的坐标来造成最后的画布的,这个坐标须要咱们根据本身的实际的数据层级以及每一个层级的个数来计算。数组
首先画布的大小是固定的,在这里我用的是宽600px,高400px。画布的是以坐上角为坐标原点。假设数据是层级是5层,从1到第5层级的数量以此为2,3,4,1,1 计算过程以下:bash
data2.push({
name : data.tasks[i].alias,
value : data.tasks[i].task_name,
y: 0,
x: 600-(120 * data.tasks[i].level),
itemStyle:{
normal:{color: color}
}
})
}
复制代码
使用echarts的setOption方法绘制图标:echarts
myChart.setOption({
title: {
text: ''
},
tooltip: {},
nodeScaleRatio: 0,
animationDurationUpdate: 1500,
animationEasingUpdate: 'quinticInOut',
series : [
{
type: 'graph',
layout: 'none',
symbolSize: 30,
roam: false,
label: {
normal: {
show: true
}
},
edgeSymbol: ['circle', 'arrow'],
edgeSymbolSize: [4, 10],
edgeLabel: {
normal: {
textStyle: {
fontSize: 20
}
}
},
data: data2,
// links: [],
links: links,
lineStyle: {
normal: {
opacity: 0.9,
width: 1,
curveness: 0
}
}
}
]
});
复制代码
还能够给节点添加事件 这里选择点击事件来展现节点详情信息,代码以下:
myChart.on("click", function (param){
if(param.dataType == "node"){
_this.setState({visible: true, param: param.data.value});
}
});
复制代码
若是你要在这里使用react的this.setState({});方法来更新组件状态的话别忘记在setOption以前,提早将this赋值给一个变量,由于在这里的点击方法里this指向的是myChart。
let _this = this;
复制代码
成品就是这个样子的
完事儿,笔芯!敬礼!!!