一开始设置Echarts的指示器axisPointer,
焦点是跟着鼠标点击的位置,但是期望的焦点是在红色折线上,如下图所示
axisPointer设置的关键代码:
tooltip: {
trigger: "axis",
triggerOn: "mousemove",
position: [-5, 0],
axisPointer: {
type: "cross",
snap: true,
label: {
show: false,
},
},
transitionDuration: 0,
backgroundColor: "#FFFFFF",
textStyle: {
color: "#3C3C3C", // 设置文字颜色
fontSize: 12,
lineHeight: 20,
},
}
查了下官方文档,没有看到可以设置axisPointer位置的属性,最后决定使用markLine来绘制axisPointer中横线
大概思路是先修改axisPointer的tpye为"line"(即只展示竖线),然后监听Echarts的mousemove、mousedown事件,根据鼠标位置获取坐标轴中对应的数据,改变markLine的位置,重新setOption(绘制横线)
解决步骤:
①修改axisPointer的tpye为"line"
②配置初始markLine,配置可参考官方markLine配置详情
设置样式(去掉箭头,改为虚线,hover不加粗等…根据需求),data为空
series: [
{
name: "收益率",
type: "line",
lineStyle: {
width: 1,
},
itemStyle: {
normal: {
color: "#FF674D",
},
},
symbol: "none",
data: yData,
// 下面的markLine才是相关代码
markLine: {
symbol: "none", //去掉箭头
animation: false,
label: {
show: false,
},
lineStyle: {
color: "black",
type: "dashed",
width: 1, // 正常时的折线宽度
},
emphasis: {
label: {
show: false,
},
lineStyle: {
color: "black",
type: "dashed",
width: 1, // hover时的折线宽度
},
},
data: [],
}
},
],
③Echarts添加监听事件
this.lineEchart.getZr().on("mousemove", (params) => {
// 获取点击位置的坐标
let pointInPixel = [params.offsetX, params.offsetY];
// containPixel为true则点击位置在坐标轴内
if (this.lineEchart.containPixel("grid", pointInPixel)) {
// 传入鼠标位置坐标进行转化
// convertFromPixel返回[x, y],x对应鼠标点击处数据的下标,y对应鼠标点击处的数值
const x = this.lineEchart.convertFromPixel({ seriesIndex: 0 }, pointInPixel)[0];
// series[0].data[x]是第一条折线上的数据
const markLineValue = lineChartOptions.series[0].data[x];
let series = lineChartOptions.series;
// 修改markLine的值
series[0].markLine.data = [{ yAxis: markLineValue }];
// 重新setOption
this.lineEchart.setOption({ series }, { lazyUpdate: true });
} else {
// 不在坐标轴内不展示markLine
let series = lineChartOptions.series;
series[0].markLine.data = [];
this.lineEchart.setOption(
{
series,
},
{ lazyUpdate: true }
);
}
});
注释都写在代码里面了,convertFromPixel获取点击处的数据下标x,之后再获取折线数据:yData[x](我这里直接从option里面取了,lineChartOptions.series[0].data[x]),再更新markLine的值,就能绘制出markLine(横线)固定在折线的效果
想了解更多可以去看看官方文档
containPixel。判断给定的点是否在指定的坐标系或者系列上;
convertFromPixel。转换像素坐标值到逻辑坐标系上的点;
setOption。每次监听mousemove都重新setOption,会导致Echarts很卡,听同事的建议,增加设置了lazyUpdate:true属性,有所缓解。
效果图如下:
至此,问题大概就解决了,大佬们有什么问题欢迎指出。