产品那边反应图表缩放要滚很久才能滚到最小的秒级,然后本身echarts datazoom配置是不支持这个功能配置的,于是通过去鼠标wheel事件去优化,思路就是找到鼠标的相对x轴的坐标,通过这个坐标去修改datazoom的start、end,就可以在原有基础上,扩大倍数,基本滚两三下就滚到底了,具体代码如下,我用的是vue-echarts,datazoom是配置的inside,x轴我是时间轴
<v-chart
ref="chart"
:autoresize="true"
:option="option"
:onZr:mousewheel="handleWheel"
@datazoom="handleDataZoom"
/>
dataZoom: {
type: 'inside', // inside: 表示用内测滑块
zoomOnMouseWheel: true, // 关闭滚轮缩放
moveOnMouseWheel: false, // 开启滚轮平移
moveOnMouseMove: true, // 鼠标移动能触发数据窗口平移
start: 0,
end: 100,
// 缩放最小是秒
minSpan: 0.02,
filterMode: 'none',
},
// 优化鼠标滚轮放大
const handleWheel = (event: any) => {
console.log('wheel event:', event);
const delta = event.wheelDelta; // 获取滚轮滚动的距离
console.log('delta:', delta);
const zoomScale = delta > 0 ? 0.4 : 4; // 定义缩放比例
// 获取当前的dataZoom状态
const dataZoomOption = chart.value?.getOption().dataZoom[0];
console.log('dataZoomOption:', dataZoomOption);
const currentStart = dataZoomOption.start;
const currentEnd = dataZoomOption.end;
const currentRange = currentEnd - currentStart;
// 获取鼠标在图表容器内的位置
const x = event.offsetX;
// 转成百分比型式
let percentage = chart.value?.convertFromPixel('xAxis', x)
? ((chart.value?.convertFromPixel('xAxis', x) - timeStart) / (timeEnd - timeStart)) * 100
: 49;
console.log('percentage:', percentage);
// 计算缩放后的新范围
const newRange = currentRange * zoomScale;
// 计算左右比例
const leftPercentage = (percentage - currentStart) / currentRange;
// const rightPercentage = (currentRange - percentage) / currentRange;
// 根据左右比例缩放
let newStart = percentage - newRange * leftPercentage;
let newEnd = percentage + newRange - newRange * leftPercentage;
// 手动去修改
chart.value?.dispatchAction({
type: 'dataZoom',
start: newStart,
end: newEnd,
});
};