需求:
01:等放大echart时候,去请求后端数据,重新渲染
02:渲染新数据后,X轴的状态不变化
03:此时Tooltip显示对应的索引数据,是旧数据的索引
方案:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="./echarts.min_5.js"></script>
<title>Document</title>
</head>
<style>
#eChart {
width: 1200px;
height: 500px;
}
</style>
<body>
<div id="eChart"></div>
<script>
var eChartDOM = document.querySelector('#eChart');
var myChart = echarts.init(eChartDOM);
var colorList = ["#9E87FF", '#73DDFF', '#fe9a8b', '#F56948', '#9E87FF']
let dataValue = [['0', '0'], ['10', '50'], ['50', '150'], ['60', '148'], ['90', '80']];
let dataValue2 = [['0', '10'], ['10', '57'], ['15', '48'], ['16', '48'], ['17', '48'], ['20', '75'], ['24', '85'], ['25', '105'], ['30', '150'], ['60', '80'], ['90', '80']];
let option = {
backgroundColor: '#0c2d55',
tooltip: {
trigger: "axis",
},
grid: {
top: '10%',
left: '7%',
right: '7%',
bottom: '10%',
},
xAxis: {
"type": "value",
"name": "距离(m)",
"splitLine": {
"show": false
},
"data": [],
"axisLine": {
"onZero": false,
"show": true
},
"max": 150,
"min": 0
},
yAxis: [
{
type: 'value',
splitLine: {
show: 0
},
axisLine: {
show: true,
lineStyle: {
color: '#008de7',
},
},
axisTick: {
show: false,
},
"max": 450,
"min": 0
},
],
series: [
{
name: '已处置数',
type: 'line',
data: dataValue,
}
],
dataZoom: [
{
"show": true,
"type": "inside",
"xAxisIndex": [
0
],
"filterMode": "none"
},
{
"type": "inside",
"show": true,
"yAxisIndex": [
0
],
"filterMode": "none"
}
]
};
myChart.setOption(option);
// 创建防抖函数
var debouncedFunc = null;
myChart.on('dataZoom', function (params) {
// 触发防抖函数
clearTimeout(debouncedFunc);
debouncedFunc = setTimeout(() => {
getViewXData();
}, 500)
});
function getViewXData() {
// 获取当前图表的配置项
var option = myChart.getOption();
// 获取X轴上的最小值、最大值和X轴类型
var xAxis = option.xAxis[0];
var minVal = xAxis.min || xAxis.data[0] || 0;
var maxVal = xAxis.max || xAxis.data[xAxis.data.length - 1] || 0;
var type = xAxis.type;
// 计算数据缩放区域的起始位置和结束位置
var zoom = option.dataZoom[0];
var startPercent = zoom.start / 100;
var endPercent = zoom.end / 100;
var totalLength = type === 'value' ? maxVal - minVal : xAxis.data.length - 1;
var startIndex = Math.round(startPercent * totalLength);
var endIndex = Math.round(endPercent * totalLength);
// 根据起始位置和结束位置计算实际展示的范围
var startVal = type === 'value' ? minVal + (maxVal - minVal) * startPercent : xAxis.data[startIndex];
var endVal = type === 'value' ? minVal + (maxVal - minVal) * endPercent : xAxis.data[endIndex];
console.log(startVal, endVal);
changeOption();
};
function changeOption() {
option.series[0].data = dataValue2;
// 手动清除 Tooltip 缓存
myChart.dispatchAction({
type: 'hideTip'
});
// 然后在开启
setTimeout(function () {
myChart.dispatchAction({
type: 'showTip',
seriesIndex: 0,
dataIndex: 0
});
}, 0);
myChart.setOption(option);
}
</script>
</body>
</html>