通过 npm 安装 Chart.js:
npm install chart.js
通过 CDN 引入 Chart.js:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
创建一个简单的折线图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chart.js Example</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<canvas id="myChart" width="400" height="200"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
data: [0, 10, 5, 2, 20, 30, 45]
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>
</body>
</html>
创建一个柱状图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chart.js Bar Chart Example</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<canvas id="barChart" width="400" height="200"></canvas>
<script>
var ctx = document.getElementById('barChart').getContext('2d');
var barChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '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: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>
</body>
</html>
Chart():创建一个新的图表实例。
var myChart = new Chart(ctx, {
type: 'line',
data: {...},
options: {...}
});
data:定义图表的数据,包括 labels 和 datasets。
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
data: [0, 10, 5, 2, 20, 30, 45]
}]
}
options:配置图表的选项,如响应式、缩放、图例等。
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
type:定义图表的类型,如 'line', 'bar', 'pie', 'radar', 'polarArea', 'bubble', 'scatter'。
type: 'bar'
update():更新图表的数据和配置。
myChart.data.datasets[0].data = [10, 20, 30, 40];
myChart.update();
destroy():销毁图表实例,释放资源。
myChart.destroy();
Chart.js 是一个功能强大且易于使用的 JavaScript 图表库,适用于各种数据可视化需求。其丰富的图表类型和配置选项,使得开发者可以快速创建高质量的图表,提升 Web 应用的数据展示效果。