实现echarts柱状图标记区域,并在单击柱状条时触发点击事件切换标记区域
<div id="main" style="width: 600px;height:400px;"></div>
let _chart = null;
letselectInfo = {};
window.addEventListener('resize', () => {
if (_chart) _chart.resize()
})
let aAxisData = [],
yAxisData1 = [],
yAxisData2 = [];
for (var i = 0; i < 15; i++) {
aAxisData.push({
id: 'id_' + i,
value: '测试' + (i + 1) + '组'
})
yAxisData1.push(i * 4 + 6);
yAxisData2.push(i * 2 + 5);
}
this.initCharts('main', aAxisData, yAxisData1, yAxisData2);
function initCharts(_id, aAxisData, yAxisData1, yAxisData2) {
if (_chart) _chart.clear();
_chart = echarts.init(document.getElementById(_id));
const options = {
grid: {
left: '5%',
right: '4%',
bottom: '30px',
top: '80px',
containLabel: true
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
},
},
xAxis: [{
type: 'category',
data: aAxisData,
axisLabel: {
show: true,
intervel: 0,
rotate: 20,
width: 120,
height: 20,
overflow: 'truncate',
ellipsis: '...'
},
max: (value) => {
value.max = value.max < 6 ? 6 : value.max;
return value.max;
}
}],
yAxis: [{
type: 'value',
}],
series: [{
name: '总数',
type: 'bar',
data: yAxisData1,
itemStyle: {
color: '#4E89EE'
},
barGap: 0,
markArea: {
silent: true,
itemStyle: {
color: 'rgba(78, 137, 238, 0.19)'
},
data: [
[{
xAxis: aAxisData[0].value
}, {
xAxis: aAxisData[0].value
}]
]
}
}, {
name: '已接入数',
type: 'bar',
data: yAxisData2,
itemStyle: {
color: '#bbd5ff'
},
}]
}
document.getElementById(_id).setAttribute('_echarts_instance_', '');
_chart.setOption(options);
this.barChartClick(_chart)
}
function barChartClick(chart) {
chart.getZr().on('click', (params) => {
let pointInPixel = [params.offsetX, params.offsetY];
if (chart.containPixel('grid', pointInPixel)) {
let pointInGrid = chart.convertFromPixel({
seriesIndex: 0
}, pointInPixel);
let handleIndex = Number(pointInGrid[0]);
let op = chart.getOption();
let dataX = op.xAxis[0].data[handleIndex];
let dataY = op.series[0].data[handleIndex];
selectInfo = dataX;
op.series[0].markArea.data = [
[{
'xAxis': dataX.value
}, {
'xAxis': dataX.value
}]
]
chart.setOption(op);
}
})
}