可以在一个 HTML 页面中显示多个 Chart.js 环形图。这里是一个例子,展示了如何在一个 HTML 页面中显示 6 个简单的环形图。

首先,在

<head>
中引入 Chart.js 库:

<head>
<title>My Charts</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>

然后,在

<body>
中添加 6 个
<canvas>
元素,用于显示 6 个环形图。这里的例子中,每个
<canvas>
元素都有一个唯一的
id
属性,方便在 JavaScript 代码中选中并对其进行设定。

<body>
<canvas id="chart1"></canvas>
<canvas id="chart2"></canvas>
<canvas id="chart3"></canvas>
<canvas id="chart4"></canvas>
<canvas id="chart5"></canvas>
<canvas id="chart6"></canvas>
</body>

编写 JavaScript 代码,在每个

<canvas>
上绘制环形图。这里的例子中,我们使用
Chart
构造函数来创建并绘制环形图。每个环形图都有一个唯一的
id
,指定了它所在的 HTML 元素。在每个环形图的选项中,我们设置了
data
(用于绘制的数据数组)和
backgroundColor
(环形图的背景色)。此外,还可以设置其他选项,例如
cutoutPercentage
(环形图的中心空洞占比)、
rotation
(环形图的旋转角度)等等。

<script>
// 环形图1
var ctx1 = document.getElementById('chart1').getContext('2d');
var chart1 = new Chart(ctx1, {
type: 'doughnut',
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [{
data: [30, 40, 20],
backgroundColor: ['#ff6384', '#36a2eb', '#ffce56']
}]
},
options: {
cutoutPercentage: 60,
rotation: -0.5 * Math.PI
}
});
// 环形图2
var ctx2 = document.getElementById('chart2').getContext('2d');
var chart2 = new Chart(ctx2, {
type: 'doughnut',
data: {
labels: ['A', 'B', 'C'],
datasets: [{
data: [10, 30, 60],
backgroundColor: ['#ff6384', '#36a2eb', '#ffce56']
}]
},
options: {
cutoutPercentage: 60,
rotation: 0.5 * Math.PI
}
});
// 环形图3
var ctx3 = document.getElementById('chart3').getContext('2d');
var chart3 = new Chart(ctx3, {
type: 'doughnut',
data: {
labels: ['One', 'Two', 'Three'],
datasets: [{
data: [40, 20, 40],
backgroundColor: ['#ff6384', '#36a2eb', '#ffce56']
}]
},
options: {
cutoutPercentage: 60,
rotation: -0.25 * Math.PI
}
});
// 环形图4
var ctx4 = document.getElementById('chart4').getContext('2d');
var chart4 = new Chart(ctx4, {
type: 'doughnut',
data: {
labels: ['First', 'Second', 'Third'],
datasets: [{
data: [25, 45, 30],
backgroundColor: ['#ff6384', '#36a2eb', '#ffce56']
}]
},
options: {
cutoutPercentage: 60,
rotation: 0.75 * Math.PI
}
});
// 环形图5
var ctx5 = document.getElementById('chart5').getContext('2d');
var chart5 = new Chart(ctx5, {
type: 'doughnut',
data: {
labels: ['X', 'Y', 'Z'],
datasets: [{
data: [15, 55, 30],
backgroundColor: ['#ff6384', '#36a2eb', '#ffce56']
}]
},
options: {
cutoutPercentage: 60,
rotation: -0.75 * Math.PI
}
});
// 环形图6
var ctx6 = document.getElementById('chart6').getContext('2d');
var chart6 = new Chart(ctx6, {
type: 'doughnut',
data: {
labels: ['Good', 'Better', 'Best'],
datasets: [{
data: [50, 25, 25],
backgroundColor: ['#ff6384', '#36a2eb', '#ffce56']
}]
},
options: {
cutoutPercentage: 60,
rotation: 0.25 * Math.PI
}
});
</script>