从零开始学Echarts制作实时数据可视化图表视频教程零基础入门
说实话,我第一次看到Echarts的时候,完全被那种动态数据流动的效果震撼到了。那时候我还在纠结怎么让网页上的数字”动”起来,现在想想,其实没那么难。今天就把我踩过的坑、走过的弯路,全部掏心窝子跟你分享。
先说说,什么是Echarts
Echarts是百度开源的一个纯JavaScript图表库,说白了就是帮你用代码把数据变成各种好看的图表——柱状图、折线图、饼图、地图、雷达图,想画啥画啥。
为什么推荐它?三个理由:
- 零门槛:不用学什么复杂的框架,会写HTML就行
- 性能好:百万级数据也能流畅渲染
- 文档友好:中文文档写得非常清楚,照着抄就能用
很多初学者最怕的是”我不知道从哪里开始”,这个恐惧我懂。所以别急,我们一点一点来。
第一步:把环境搭起来
不用装什么Node.js、不用配Webpack,你就需要一个普通的HTML文件。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>实时数据可视化</title>
<style>
#main {
width: 1000px;
height: 600px;
margin: 0 auto;
background: #1a1a2e;
}
</style>
<!-- 引入Echarts -->
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
</head>
<body>
<div id="main"></div>
<script src="app.js"></script>
</body>
</html>
看到了吗?就两行关键代码:
- 引入Echarts的CDN链接
- 准备一个容器div
就这么简单,环境就搭好了。
第二步:写你的第一个静态图表
先别想着实时数据,咱们先把图表画出来。创建一个app.js文件:
// 初始化echarts实例
var chart = echarts.init(document.getElementById('main'));
// 配置项
var option = {
backgroundColor: '#1a1a2e',
title: {
text: '服务器CPU使用率监控',
textStyle: { color: '#00d4ff', fontSize: 22 }
},
tooltip: {
trigger: 'axis',
backgroundColor: 'rgba(0,0,0,0.7)',
textStyle: { color: '#fff' }
},
xAxis: {
type: 'category',
data: ['10:00', '10:05', '10:10', '10:15', '10:20', '10:25', '10:30'],
axisLine: { lineStyle: { color: '#444' } },
axisLabel: { color: '#aaa' }
},
yAxis: {
type: 'value',
max: 100,
axisLine: { lineStyle: { color: '#444' } },
axisLabel: { color: '#aaa' },
splitLine: { lineStyle: { color: '#333' } }
},
series: [{
name: 'CPU使用率',
type: 'line',
data: [30, 45, 60, 55, 70, 85, 65],
smooth: true,
symbol: 'circle',
symbolSize: 8,
lineStyle: { color: '#00d4ff', width: 3 },
itemStyle: { color: '#00d4ff' },
areaStyle: {
color: {
type: 'linear',
x: 0, y: 0, x2: 0, y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(0,212,255,0.4)' },
{ offset: 1, color: 'rgba(0,212,255,0)' }
]
}
}
}]
};
// 使用配置项绘制图表
chart.setOption(option);
双击打开HTML文件,你应该能看到一条漂亮的折线图。别急,这只是静态的——接下来才是真正的重头戏。
第三步:让数据动起来(核心部分)
实时数据可视化的本质就三件事:
有数据源 → 定时更新 → 图表刷新
我们来模拟一个场景:每隔2秒,CPU使用率生成一个随机值,图表实时刷新。
var chart = echarts.init(document.getElementById('main'));
// 初始化数据
var categories = [];
var cpuData = [];
// 预填充30个时间点
for (var i = 0; i < 30; i++) {
var time = new Date(Date.now() - (30 - i) * 2000);
categories.push(formatTime(time));
cpuData.push(Math.floor(Math.random() * 60 + 20)); // 20~80随机值
}
var option = {
backgroundColor: '#1a1a2e',
title: {
text: '实时CPU监控',
textStyle: { color: '#00d4ff', fontSize: 20 }
},
tooltip: {
trigger: 'axis',
backgroundColor: 'rgba(0,0,0,0.7)',
textStyle: { color: '#fff' }
},
legend: {
data: ['CPU使用率'],
textStyle: { color: '#aaa' },
top: 30
},
grid: {
left: '5%',
right: '5%',
bottom: '10%',
containLabel: true
},
xAxis: {
type: 'category',
boundaryGap: false,
data: categories,
axisLine: { lineStyle: { color: '#444' } },
axisLabel: { color: '#aaa', fontSize: 11 }
},
yAxis: {
type: 'value',
min: 0,
max: 100,
axisLine: { lineStyle: { color: '#444' } },
axisLabel: { color: '#aaa' },
splitLine: { lineStyle: { color: '#2a2a4a' } }
},
series: [{
name: 'CPU使用率',
type: 'line',
data: cpuData,
smooth: true,
symbol: 'none',
lineStyle: { color: '#00d4ff', width: 2 },
areaStyle: {
color: {
type: 'linear',
x: 0, y: 0, x2: 0, y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(0,212,255,0.3)' },
{ offset: 1, color: 'rgba(0,212,255,0)' }
]
}
}
}]
};
chart.setOption(option);
// 关键:每2秒更新一次数据
setInterval(function () {
var now = new Date();
// 移除最旧的数据
categories.shift();
cpuData.shift();
// 添加新数据
categories.push(formatTime(now));
// 模拟真实CPU波动:在前一个值附近小幅变化
var lastValue = cpuData[cpuData.length - 1] || 50;
var newValue = Math.max(5, Math.min(95, lastValue + (Math.random() - 0.5) * 20));
cpuData.push(Math.round(newValue));
// 更新图表
chart.setOption({
xAxis: { data: categories },
series: [{ data: cpuData }]
});
}, 2000);
function formatTime(date) {
var h = date.getHours().toString().padStart(2, '0');
var m = date.getMinutes().toString().padStart(2, '0');
var s = date.getSeconds().toString().padStart(2, '0');
return h + ':' + m + ':' + s;
}
刷新页面,你会发现曲线在实时流动。这就是实时数据可视化的核心逻辑。
第四步:接入真实数据源(WebSocket)
上面那个例子用的是随机数模拟,实战中你大概率要接后端API。最优雅的方式是用WebSocket,因为它是全双工通信,服务器可以主动推数据给你。
var chart = echarts.init(document.getElementById('main'));
// WebSocket连接
var ws = new WebSocket('wss://your-server.com/realtime');
// 存储数据
var categories = [];
var cpuData = [];
var memData = [];
// 预填充数据,避免一开始图表是空的
for (var i = 0; i < 30; i++) {
categories.push('');
cpuData.push(0);
memData.push(0);
}
var option = {
backgroundColor: '#0d1117',
title: {
text: '服务器实时监控面板',
textStyle: { color: '#58a6ff', fontSize: 20 }
},
tooltip: { trigger: 'axis' },
legend: {
data: ['CPU', '内存'],
textStyle: { color: '#8b949e' },
top: 35
},
grid: {
left: '3%', right: '4%', bottom: '8%', containLabel: true
},
xAxis: {
type: 'category',
boundaryGap: false,
data: categories,
axisLine: { lineStyle: { color: '#30363d' } },
axisLabel: { color: '#8b949e', fontSize: 10 }
},
yAxis: {
type: 'value',
min: 0, max: 100,
axisLine: { lineStyle: { color: '#30363d' } },
axisLabel: { color: '#8b949e' },
splitLine: { lineStyle: { color: '#21262d' } }
},
series: [
{
name: 'CPU',
type: 'line',
data: cpuData,
smooth: true,
symbol: 'none',
lineStyle: { color: '#58a6ff', width: 2 },
areaStyle: {
color: {
type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(88,166,255,0.3)' },
{ offset: 1, color: 'rgba(88,166,255,0)' }
]
}
}
},
{
name: '内存',
type: 'line',
data: memData,
smooth: true,
symbol: 'none',
lineStyle: { color: '#3fb950', width: 2 },
areaStyle: {
color: {
type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(63,185,80,0.3)' },
{ offset: 1, color: 'rgba(63,185,80,0)' }
]
}
}
}
]
};
chart.setOption(option);
// 监听WebSocket消息
ws.onmessage = function(event) {
var data = JSON.parse(event.data);
// 移除最旧的点,保持最多显示30个
categories.shift();
cpuData.shift();
memData.shift();
// 添加新的时间点
categories.push(formatTime(new Date()));
cpuData.push(data.cpu);
memData.push(data.memory);
// 增量更新,性能更好
chart.setOption({
xAxis: { data: categories },
series: [
{ data: cpuData },
{ data: memData }
]
});
};
ws.onerror = function() {
console.error('WebSocket连接失败');
};
ws.onclose = function() {
console.log('WebSocket已关闭');
};
function formatTime(date) {
return date.toTimeString().slice(0, 8);
}
几个实战小技巧:
- 用
chart.setOption()而不是每次都重新渲染,性能会好很多 - 数据点别超过50个,多了页面会卡
- WebSocket断开时要做重连处理,不然刷新后就看不到数据了
第五步:WebSocket断线重连
线上项目最怕的就是连接中断,你得有自愈能力:
var ws;
var reconnectDelay = 1000; // 初始重连间隔1秒
function connect() {
ws = new WebSocket('wss://your-server.com/realtime');
ws.onopen = function() {
console.log('连接成功');
reconnectDelay = 1000; // 重置延迟
};
ws.onmessage = function(event) {
handleData(event.data);
};
ws.onerror = function() {
console.warn('连接出错,准备重连...');
};
ws.onclose = function() {
console.warn('连接断开,' + reconnectDelay + 'ms后重连');
setTimeout(connect, reconnectDelay);
// 指数退避,最多等30秒
reconnectDelay = Math.min(reconnectDelay * 2, 30000);
};
}
function handleData(data) {
var parsed = JSON.parse(data);
categories.shift();
cpuData.shift();
memData.shift();
categories.push(formatTime(new Date()));
cpuData.push(parsed.cpu);
memData.push(parsed.memory);
chart.setOption({
xAxis: { data: categories },
series: [{ data: cpuData }, { data: memData }]
});
}
// 启动连接
connect();
这个重连逻辑用到了指数退避——第一次等1秒,第二次2秒,第三次4秒……直到30秒为止。这样不会因为频繁重连把服务器打爆。
常见问题排雷
Q: 数据量大了之后页面卡成PPT怎么办?
A: 限制显示的数据点数量。超过50个点就移除最早的,同时可以加一个采样逻辑——每5条数据只保留1条。
// 采样:只保留每5个中的第1个
if (categories.length > 50) {
categories = categories.filter((_, i) => i % 5 === 0);
cpuData = cpuData.filter((_, i) => i % 5 === 0);
}
Q: 图表渲染闪烁?
A: 确保每次调用setOption时,传入的是完整的配置,而不是部分配置。Echarts的option是合并逻辑,漏传属性可能导致样式异常。
Q: 想做多图表联动怎么办?
A: 用echarts.connect()把多个实例连起来,一个图表操作,其他的跟着动。
var chart1 = echarts.init(document.getElementById('chart1'));
var chart2 = echarts.init(document.getElementById('chart2'));
// 联动
echarts.connect([chart1, chart2]);
完整项目结构
一个像样的实时监控面板,建议这样组织文件:
project/
├── index.html # 主页面
├── css/
│ └── style.css # 样式
├── js/
│ ├── app.js # 主逻辑
│ ├── charts.js # 图表封装
│ └── websocket.js # WebSocket封装
└── assets/
└── icons/
不要把所有代码都塞进一个文件,那以后改起来会怀疑人生。
最后说几句
学Echarts做实时数据可视化,最难的从来不是技术本身,而是”第一步”。很多人看了十几种教程,就是不敢动手写第一行代码。
你现在已经知道完整流程了:初始化 → 画静态图 → 定时更新 → 接WebSocket → 做重连 → 优化性能。每一步都有代码示例,照着敲一遍,比看十遍视频管用。
如果你做完之后遇到报错,别慌,把错误信息复制给AI,十有八九都能解决。代码这事儿,多练就好,没有人天生就会。
