实时更新图表
在 Chart.js 中,通过周期性地修改数据并调用 update() 方法,可以实现实时更新图表的效果。这种方式广泛用于展示传感器数据、系统监控、用户行为数据等实时信息。
下面演示一个简单的实时折线图,每秒生成一个新点并追加到图表中,同时移除最旧的数据点,形成滚动式图表。
(function () {
const ctx = document.getElementById("liveChart").getContext("2d");
const labels = Array.from({ length: 10 }, (_, i) => `${i}s`);
const data = {
labels,
datasets: [
{
label: "实时数据",
data: Array.from({ length: 10 }, () => Math.random() * 100),
borderColor: "rgb(255, 99, 132)",
tension: 0.4,
},
],
};
const config = {
type: "line",
data,
options: {
responsive: true,
animation: false,
scales: {
y: {
min: 0,
max: 100,
},
},
},
};
const chart = new Chart(ctx, config);
setInterval(() => {
const newTime = `${parseInt(labels[labels.length - 1]) + 1}s`;
labels.push(newTime);
labels.shift();
chart.data.datasets[0].data.push(Math.random() * 100);
chart.data.datasets[0].data.shift();
chart.update();
}, 1000);
})();
源码
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>实时更新图表</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body {
max-width: 700px;
margin: 2rem auto;
font-family: sans-serif;
background: #f9f9f9;
padding: 1rem;
text-align: center;
}
canvas {
background: #fff;
border: 1px solid #ccc;
margin: 1rem auto;
}
</style>
</head>
<body>
<canvas id="liveChart" width="700" height="400"></canvas>
<script>
(function () {
const ctx = document.getElementById(‘liveChart’).getContext(‘2d’);
const labels = Array.from({ length: 10 }, (_, i) => ${i}s);
const data = {
labels,
datasets: [{
label: ‘实时数据’,
data: Array.from({ length: 10 }, () => Math.random() * 100),
borderColor: ‘rgb(255, 99, 132)’,
tension: 0.4
}]
};
const config = {
type: 'line',
data,
options: {
responsive: true,
animation: false,
scales: {
y: {
min: 0,
max: 100
}
}
}
};
const chart = new Chart(ctx, config);
setInterval(() => {
const newTime = `${parseInt(labels[labels.length - 1]) + 1}s`;
labels.push(newTime);
labels.shift();
chart.data.datasets[0].data.push(Math.random() * 100);
chart.data.datasets[0].data.shift();
chart.update();
}, 1000);
})();
</script>
</body>
</html>
相关内容
- 什么是 Chart.js? Chart.js 是一个简单易用且功能强大的 JavaScript 图表库,支持多种常见图表类型,帮助开发者快速创建美观且响应式的数据可视化效果,适合初学者和专...
- 安装与引入 介绍如何在项目中安装和引入 Chart.js,包括通过 CDN 快速使用和通过 npm 安装到前端构建环境的多种方式,帮助快速搭建图表开发环境。
- 基本结构与初始化 讲解如何创建图表的基本结构与初始化流程,包括配置画布、准备数据和实例化图表的步骤,帮助快速搭建图表展示。
- 示例:折线图 通过示例讲解如何创建折线图,涵盖数据配置、样式设置和基本交互,帮助快速掌握折线图的绘制技巧。
- 折线图 Line 介绍如何使用 Chart.js 创建折线图,详细讲解数据配置、样式调整及交互功能,帮助快速制作趋势图表。
- 柱状图 Bar 介绍如何使用 Chart.js 创建柱状图,详细讲解数据配置、颜色设置及图表样式,帮助快速绘制直观的条形数据展示。