Echarts在实际业务中,肯定会有很多涉及交互,在此总结一下近期业务常用到的点击事件。
1. 基本点击事件
myChart.on('click', (param) => {
// 当前点击的索引,默认只可以点击(如柱状图bar,折线图折点)
console.log(param.dataIndex)
})
2. 如何点击坐标轴文字
// 坐标轴配置项新增如下配置,示例为X轴,y轴相同配置
xAxis: {
silent: false, //坐标轴是否是静态无法交互。
triggerEvent: true, //坐标轴的标签是否响应和触发鼠标事件,默认不响应。
}
// 点击事件
myChart.on('click', (param) => {
// 坐标轴
if(param.componentType === 'xAxis'){
// 业务代码
}
})
3. 鼠标事件的所有属性
基本参数如下,其它图表诸如饼图可能会有部分附加参数。例如饼图会有percent
属性表示百分比,具体见各个图表类型的 label formatter 回调函数的 params
。
{
// 当前点击的图形元素所属的组件名称,
// 其值如 'series'、'markLine'、'markPoint'、'timeLine' 等。
componentType: string,
// 系列类型。值可能为:'line'、'bar'、'pie' 等。当 componentType 为 'series' 时有意义。
seriesType: string,
// 系列在传入的 option.series 中的 index。当 componentType 为 'series' 时有意义。
seriesIndex: number,
// 系列名称。当 componentType 为 'series' 时有意义。
seriesName: string,
// 数据名,类目名
name: string,
// 数据在传入的 data 数组中的 index
dataIndex: number,
// 传入的原始数据项
data: Object,
// sankey、graph 等图表同时含有 nodeData 和 edgeData 两种 data,
// dataType 的值会是 'node' 或者 'edge',表示当前点击在 node 还是 edge 上。
// 其他大部分图表中只有一种 data,dataType 无意义。
dataType: string,
// 传入的数据值
value: number|Array,
// 数据图形的颜色。当 componentType 为 'series' 时有意义。
color: string,
// 用户自定义的数据。只在 graphic component 和自定义系列(custom series)
// 中生效,如果节点定义上设置了如:{type: 'circle', info: {some: 123}}。
info: *
}
4. 全局点击事件
myChart.getZr().on('click', param => {
const pointInPixel = [param.offsetX, param.offsetY]
// 判断给定的点是否在指定的坐标系或者系列上
if (myChart.containPixel('grid', pointInPixel)) {
// 获取到点击的 x轴 下标 转换为逻辑坐标
let xIndex = myChart.convertFromPixel({ seriesIndex: 0 },pointInPixel)[0]
// 业务代码
console.log(xIndex)
}
})