js实现chart
使用 Chart.js 绘制图表
Chart.js 是一个流行的 JavaScript 库,用于创建响应式、交互式的图表。以下是使用 Chart.js 绘制图表的基本方法。
安装 Chart.js 通过 CDN 引入:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
通过 npm 安装:
npm install chart.js
创建简单的柱状图
HTML 结构:
<canvas id="myChart" width="400" height="400"></canvas>
JavaScript 代码:

const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
创建折线图
只需将 type 改为 'line':
const myChart = new Chart(ctx, {
type: 'line',
data: {
// 数据配置与柱状图类似
}
});
创建饼图
将 type 改为 'pie':
const myChart = new Chart(ctx, {
type: 'pie',
data: {
// 数据配置
}
});
响应式设计
Chart.js 图表默认是响应式的。如果需要调整响应式行为,可以在 options 中配置:

options: {
responsive: true,
maintainAspectRatio: false
}
动态更新数据
可以通过更新数据集来动态修改图表数据:
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
function removeData(chart) {
chart.data.labels.pop();
chart.data.datasets.forEach((dataset) => {
dataset.data.pop();
});
chart.update();
}
自定义配置
Chart.js 提供了丰富的配置选项来自定义图表外观和行为:
options: {
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Custom Chart Title'
}
}
}
销毁图表
当不再需要图表时,可以销毁它以释放资源:
myChart.destroy();
Chart.js 支持多种图表类型,包括柱状图、折线图、饼图、雷达图等,每种类型都有特定的配置选项。官方文档提供了完整的 API 参考和示例。






