Chart.js 是一个基于 HTML5 Canvas 的 JavaScript 图表库,它允许开发者创建各种类型的图表,如折线图、柱状图、饼图等。每个图表都由一组配置选项(options)和一个数据集(dataset)组成。
Chart.js 支持以下几种主要图表类型:
假设我们有两个柱状图,它们的配置相同但数据不同。我们可以通过以下步骤来实现:
<div>
<canvas id="chart1"></canvas>
<canvas id="chart2"></canvas>
</div>
// 引入 Chart.js 库
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// 定义相同的配置选项
const commonOptions = {
scales: {
y: {
beginAtZero: true
}
}
};
// 数据集1
const data1 = {
labels: ['January', 'February', 'March', 'April', 'May'],
datasets: [{
label: 'Dataset 1',
data: [65, 59, 80, 81, 56],
backgroundColor: 'rgba(75, 192, 192, 0.2)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
}]
};
// 数据集2
const data2 = {
labels: ['January', 'February', 'March', 'April', 'May'],
datasets: [{
label: 'Dataset 2',
data: [28, 48, 40, 19, 86],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
}]
};
// 创建图表1
const ctx1 = document.getElementById('chart1').getContext('2d');
new Chart(ctx1, {
type: 'bar',
data: data1,
options: commonOptions
});
// 创建图表2
const ctx2 = document.getElementById('chart2').getContext('2d');
new Chart(ctx2, {
type: 'bar',
data: data2,
options: commonOptions
});
</script>
原因:
解决方法:
labels
和 datasets
。window.onload
或 document.addEventListener('DOMContentLoaded', ...)
。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multiple Charts</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div>
<canvas id="chart1"></canvas>
<canvas id="chart2"></canvas>
</div>
<script>
window.onload = function() {
const commonOptions = {
scales: {
y: {
beginAtZero: true
}
}
};
const data1 = {
labels: ['January', 'February', 'March', 'April', 'May'],
datasets: [{
label: 'Dataset 1',
data: [65, 59, 80, 81, 56],
backgroundColor: 'rgba(75, 192, 192, 0.2)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
}]
};
const data2 = {
labels: ['January', 'February', 'March', 'April', 'May'],
datasets: [{
label: 'Dataset 2',
data: [28, 48, 40, 19, 86],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
}]
};
const ctx1 = document.getElementById('chart1').getContext('2d');
new Chart(ctx1, {
type: 'bar',
data: data1,
options: commonOptions
});
const ctx2 = document.getElementById('chart2').getContext('2d');
new Chart(ctx2, {
type: 'bar',
data: data2,
options: commonOptions
});
};
</script>
</body>
</html>
通过以上步骤和示例代码,你可以轻松地创建多个配置相同但数据不同的 Chart.js 图表。如果遇到问题,可以参考上述解决方法进行排查。
领取专属 10元无门槛券
手把手带您无忧上云