在 ECharts 折线图中,要获取当前显示图例及图例对应颜色,可通过监听图例点击事件来实现。以下是一个示例代码:
```javascript
// 初始化 ECharts 实例
var myChart = echarts.init(document.getElementById('main'));
// 配置项
var option = {
legend: {
orient: 'horizontal',
x: 'center',
y: 'top',
itemGap: 5,
textStyle: {
fontSize: 12,
color: '#ffffff'
},
data: ['小组1', '小组2'],
backgroundColor: 'rgba(0,0,0,0)',
borderColor: '#ccc',
borderWidth: 0,
padding: 5,
itemGap: 10,
itemWidth: 20,
itemHeight: 14
},
xAxis: {
type: 'category',
data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
},
yAxis: {
type: 'value'
},
series: [
{
name: '小组1',
data: [20, 25, 26, 22, 24, 21, 44, 11, 31, 14, 16, 16],
itemStyle: {
normal: {
color: "red",
lineStyle: {
color: 'red'
}
}
},
symbol: 'circle',
symbolSize: 10,
type: 'line'
},
{
name: '小组2',
data: [10, 15, 16, 12, 14, 11, 34, 1, 21, 4, 6, 6],
itemStyle: {
normal: {
color: "blue",
lineStyle: {
color: 'blue'
}
}
},
symbol: 'circle',
symbolSize: 10,
type: 'line'
}
]
};
// 使用配置项显示图表
myChart.setOption(option);
// 监听图例点击事件
myChart.on('legendselectchanged', function (params) {
// 获取当前点击的图例名称
var legendName = params.name;
// 遍历 series 找到对应图例的颜色
var series = option.series;
var legendColor;
for (var i = 0; i < series.length; i++) {
if (series[i].name === legendName) {
legendColor = series[i].itemStyle.normal.color;
break;
}
}
// 输出当前点击的图例名称和对应颜色
console.log('当前点击的图例名称: ', legendName);
console.log('该图例对应颜色: ', legendColor);
});
```
在上述代码中,首先初始化 ECharts 实例并设置配置项。接着,使用 `myChart.on('legendselectchanged', ...)` 方法监听图例的点击事件。当图例被点击时,通过 `params.name` 获取当前点击的图例名称。然后,遍历 `option.series` 数组,找到与点击图例名称对应的 `series` 项,并从中获取该图例对应的颜色。最后,将当前点击的图例名称和对应颜色输出到控制台[^2]。