
ec.png
代碼如下:(methods里)
myChart = this.$echarts.init(document.getElementById("myChart"))
myChart.setOption(this.option)
// 給整個(gè)畫布添加點(diǎn)擊事件
myChart.getZr().on('click', function (param) {
const pointInPixel = [param.offsetX, param.offsetY]
console.log('pointInPixel', pointInPixel)
// 使用 convertFromPixel方法 轉(zhuǎn)換像素坐標(biāo)值到邏輯坐標(biāo)系上的點(diǎn)。獲取點(diǎn)擊位置對應(yīng)的x軸數(shù)據(jù)的索引 值,借助于索引值的獲取到其它的信息
// 轉(zhuǎn)換X軸坐標(biāo)
let pointInGrid = myChart.convertFromPixel({ seriesIndex: 0 }, pointInPixel);
// 轉(zhuǎn)換Y軸坐標(biāo)
let pointInGrid2 = myChart.convertFromPixel({ seriesIndex: 1 }, pointInPixel);
// x軸數(shù)據(jù)的索引值
console.log('pointInGrid', pointInGrid2)
// 所點(diǎn)擊點(diǎn)的X軸坐標(biāo)點(diǎn)所在X軸data的下標(biāo)
let xIndex = pointInGrid[0];
// 所點(diǎn)擊點(diǎn)的Y軸坐標(biāo)點(diǎn)數(shù)值
let yIndex = pointInGrid2[1];
// 使用getOption() 獲取圖表的option
let op = myChart.getOption();
//獲取到x軸的索引值和option之后,我們就可以獲取我們需要的任意數(shù)據(jù)。
// 點(diǎn)擊點(diǎn)的X軸對應(yīng)坐標(biāo)的名稱
var time = op.xAxis[0].data[xIndex];
// 點(diǎn)擊點(diǎn)的series -- data對應(yīng)的值
var value = op.series[0].data[xIndex];
console.log('val', time)
});
data中option內(nèi)容
option:{
tooltip:{
show:true,
trigger:"item"
},
legend:{
show:true,
},
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value',
// data: [300, 600, 900, 1200, 1500, 1900],
boundaryGap: [0, '30%']
},
series:[
{
name:"折線圖",
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line',
},
{
name:"折線圖2",
data: [620, 654, 500, 800, 900, 1000, 1100],
type: 'line',
itemStyle:{//隨機(jī)顏色
color:"rgba("+ Math.floor(Math.random()*256) + ',' + Math.floor(Math.random()*256) + ',' +Math.floor(Math.random()*256) + ',' + (Math.random()*10).toFixed(1) +')'
}
}
]
},