import * as React from 'react';
import * as echarts from 'echarts';
interface Props {
name?: string;
}
export default function EchartsLine(props: Props) {
const tem = (function () {
const res = [];
let len = 5;
while (len--) {
res.push(Math.round(Math.random() * 3));
}
return res;
})();
const temup = (function () {
const res = [];
let len = 5;
while (len--) {
res.push(-Math.random().toFixed(1));
}
return res;
})();
const time = (function () {
// 立即执行函数
let now = new Date(); // 获得当前的时间
const res = []; // 存放时间的数组
let len = 5; // 要存几个时间?
while (len--) {
res.unshift(now.toLocaleTimeString().replace(/^\D*/, '')); // 转换时间,大家可以打印出来看一下
now = new Date(+now - 2000); // 延迟几秒存储一次?
}
return res;
})();
let max = Math.max(...tem, ...temup);
let min = Math.min(...tem, ...temup);
function timer(myChart) {
return setInterval(function () {
const nowTime = new Date().toLocaleTimeString().replace(/^\D*/, '');
time.push(nowTime);
tem.push(Math.round(Math.random() * 3));
temup.push(Math.random().toFixed(1));
max = Math.max(...tem, ...temup);
min = Math.min(...tem, ...temup);
//很多朋友可能要接后端接口,把数据替换下来既可以了
// axios.get('你的url').then(res => {
// console.log(res)
// })
// console.log(time, tem, temup);
myChart.setOption({
xAxis: [
{
data: time,
},
],
yAxis: {
type: 'value',
max: max,
min: min,
splitNumber: '10',
axisLabel: {
formatter: '{value}',
},
},
series: [
{
data: tem,
},
{
data: temup,
},
],
});
}, 2000);
}
React.useEffect(() => {
const myChart = echarts.init(document.getElementById(props.name));
const option = {
tooltip: {
trigger: 'axis',
},
xAxis: {
type: 'category',
boundaryGap: true,
data: time,
axisTick: {
show: false,
},
},
legend: {
left: '2%',
top: 'middle',
orient: 'vertical',
},
grid: {
left: '12%',
},
dataZoom: [
{
show: true,
realtime: true,
start: 0,
end: 100,
xAxisIndex: [0, 1],
},
{
type: 'inside',
realtime: true,
start: 0,
end: 100,
xAxisIndex: [0, 1],
},
],
yAxis: {
type: 'value',
max: max,
min: min,
splitNumber: '10',
axisLabel: {
formatter: '{value}',
},
},
series: [
{
data: tem,
type: 'line',
emphasis: {
focus: 'series',
},
itemStyle: {
normal: {
// color: '#fff', //图例的颜色
lineStyle: {},
},
},
// symbol: 'circle', //设定为实心点
// symbolSize: 10, //设定实心点的大小
name: props.name == 'temperature' ? '温度' : '电流',
},
{
data: temup,
type: 'line',
name: props.name == 'temperature' ? '温升' : '电压',
},
],
};
timer(myChart);
myChart.setOption(option);
}, []);
return <div id={props.name} style={{ width: '100%', height: '400px' }}></div>;
}