在項目開發(fā)中經(jīng)常會用到各種圖表谆级,會對圖表進行一些操作曲聂,此dome以Echarts
為例
// charts.tsx
import React, { FC, useRef, useMemo, useState, useEffect } from 'react'
import * as echarts from 'echarts'
import { useMount, useUpdateEffect } from 'ahooks'
export const Charts:FC<any> = (props) => {
const chartContainer = useRef<HTMLDivElement>(null)
const [myChart, setMyChart] = useState<echarts.ECharts | null>(null)
const defaultOptions = useMemo(
() => ({
tooltip: {
trigger: 'axis',
},
color:['red','blue'],
legend: {
data: [],
},
grid: {
top: '30px',
left: '40px',
right: '15px',
bottom: '30px',
containLabel: true, // 邊距自適應
},
xAxis: {
type: 'time',
boundaryGap: false,
},
yAxis: {
type: 'value',
},
series: [{
type: 'line',
data: [1,2,3,4,5,6],
sampling: 'lttb', // 數(shù)據(jù)采集颜武,大數(shù)據(jù)量需要配置
connectNulls: true, //斷線連接
emphasis: {
focus: 'series',
}
}]
}), [])
useMount(() => {
const echart = echarts.init(chartContainer.current!)
setMyChart(echart)
})
// 獲取xy軸最大最小值
useEffect(() => {
if (!myChart) return
const chartInstance = echarts.getInstanceByDom(ChartRef.current!) as any
setTimeout(() => {
const yAxisExtent = chartInstance.getModel().getComponent('yAxis').axis.scale._extent;
const xAxisExtent = chartInstance.getModel().getComponent('xAxis').axis.scale._extent;
console.log('====================================');
console.log(xAxisExtent, yAxisExtent);
console.log('====================================');
}, 0);
}, [myChart])
// 設(shè)置 選中chart區(qū)域 展示詳情 + 雙擊恢復
useEffect(() => {
if (myChart) {
myChart.setOption({
toolbox: {
feature: {
dataZoom: {
show: true,
iconStyle: {
opacity: 0,
},
title: {
zoom: '',
back: ''
},
yAxisIndex: 'none',
brushStyle: {
color: '#1890ff',
opacity: 0.2
},
},
},
},
});
// 獲取x軸位置
myChart.getZr().on('mousemove', (params) => {
const pointInPixel = [params.offsetX, params.offsetY]
if (myChart.containPixel('grid', pointInPixel)) {
const pointInGrid = myChart.convertFromPixel({
seriesIndex: 0
}, pointInPixel)
const xIndex = pointInGrid[0]
const data = myChart.getOption() as any
console.log(data.xAxis[0].data[Number(xIndex)])
}
})
// echarts畫布縮放
myChart.dispatchAction({
type: 'takeGlobalCursor',
key: 'dataZoomSelect',
dataZoomSelectActive: true,
});
// 雙擊恢復
myChart.getZr().on('dblclick', () => {
myChart.dispatchAction({
type: 'dataZoom',
// startValue: 0,
// endValue: 100,
start: 0,
end: 100
});
});
}
},[])
return <div ref="chartContainer"></div>
}