echarts提供了拖拽方法基础
echarts拖拽实现
开始
使用的echarts是 <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.1/dist/echarts.min.js"></script>
series.length = 2;
给节点添加graphic类,注意要在基础的setOption上重新setOption。在拖拽事件onPointDragging中根据此节点的数据找到在原始数据中的index,进行更新
实现代码
Node数据结构:{
name: data.name,
draggable: false,
symbolSize: 10,
//设置x,y
x: data.x,
y: data.y
}
}
chart1.setOption({
graphic: [...setGraphicNode(0, onPointDragging, Nodes), ...setGraphicNode(1, onPointDragging, Nodes2)]
});
// 拖拽某个圆点的过程中会不断调用此函数。
// 此函数中会根据拖拽后的新位置,改变 serise.data 中的值,并用新的 data 值,重绘图,从而使图同步于被拖拽的隐藏圆点。
function onPointDragging(dataIndex, seriesIndex=0, nodearr) {
// 这里的 data 就是本文最初的代码块中声明的 data,在这里会被更新。
//将此节点绝对的像素位置位置转为图表中位置
let newp = chart1.convertFromPixel({ 'seriesIndex': seriesIndex }, this.position);
option.series[seriesIndex].data[dataIndex] = Object.assign(option.series[seriesIndex].data[dataIndex],
{
x: newp[0],
y: newp[1]
}
)
//找到节点数据中的data,更新原始数据
nodearr.datas.some(n => {
if (n.name === option.series[seriesIndex].data[dataIndex].name) {
n.x = newp[0], n.y = newp[1];
return true;
}
});
//打印移动后的节点数据,可以用于更新原始数据
console.log('new nodes data', nodearr);
// 用更新后的 serisedata,重绘图。
chart1.setOption({
series: [
{
data: option.series[0].data
},
{
data: option.series[1].data
}
]
});
}
//给根据已有节点给关系图上节点上覆盖拖动节点
function setGraphicNode(seriesIndex=0, fn, nodearr) {
return echarts.util.map(option.series[seriesIndex].data, function (item, dataIndex) {
//使用图形元素组件在节点上划出一个隐形的图形覆盖住节点
//将图表中的位置转为像素位置
let tmpPos = chart1.convertToPixel({ 'seriesIndex': seriesIndex }, [item.x, item.y]);
return {
type: 'circle',
name: item.name,
position: tmpPos,
shape: {
cx: 0,
cy: 0,
r: 15
},
invisible: false,
draggable: true,
nodeType: item.type,
dataIndex,
//添加拖拽事件,节点的dataIndex,节点所在seriesIndex,节点的原始数据
ondrag: echarts.util.curry(fn, dataIndex, seriesIndex, nodearr),
z: 100
}
})
}