如何使用ChartJS创建甜甜圈图
时间:2020-02-23 14:45:51 来源:igfitidea点击:
在本教程中,我们将学习使用ChartJS和一些静态数据绘制甜甜圈图。
项目结构
我们将从以下项目结构开始。
在css文件夹内,我们将创建一个default.css文件。
这将包含默认样式表。
在js文件夹中,我们将创建doughnut.js文件。
在此文件中,我们将编写代码以创建甜甜圈图。
在项目文件夹中,我们将创建一个doughnut.html文件。
现在,项目结构如下所示。
我的其他教程中的上图中显示了一些其他文件。
本教程类似于饼图教程。
oughnut.html
<!DOCTYPE html>
<html>
<head>
<title>ChartJS - Doughnut</title>
<link type="text/css" rel="stylesheet" href="css/default.css"
</head>
<body>
<div class="chart-container">
<div class="doughnut-chart-container">
<canvas id="doughnut-chartcanvas-1"></canvas>
</div>
<div class="doughnut-chart-container">
<canvas id="doughnut-chartcanvas-2"></canvas>
</div>
</div>
<!-- javascript -->
<script src="js/jquery.min.js"></script>
<script src="js/Chart.min.js"></script>
<script src="js/doughnut.js"></script>
</body>
</html>
default.css
default.css文件将包含以下内容。
.chart-container {
width: 80%;
height: 480px;
margin: 0 auto;
}
.pie-chart-container,
.doughnut-chart-container {
height: 360px;
width: 360px;
float: left;
}
JavaScript
要绘制甜甜圈图,我们将编写一些javascript。
canvas
首先,通过编写以下代码,我们将使用它们各自的ids" doughnut-chartcanvas-1"和doughnut-chartcanvas-2获取这两个画布。
//get the doughnut chart canvas
var ctx1 = $("#doughnut-chartcanvas-1");
var ctx2 = $("#doughnut-chartcanvas-2");
选项
这类似于饼图选项。
//options
var options = {
responsive: true,
title: {
display: true,
position: "top",
text: "Doughnut Chart",
fontSize: 18,
fontColor: "#111"
},
legend: {
display: true,
position: "bottom",
labels: {
fontColor: "#333",
fontSize: 16
}
}
};
数据
这类似于饼图数据。
实例化Chart类
我们创建两个变量chart1和chart2并实例化Chart类。
我们传递ctx1和ctx2来保存画布和数据对象。
我们的oughnutnut.js文件的最终代码
$(function(){
//get the doughnut chart canvas
var ctx1 = $("#doughnut-chartcanvas-1");
var ctx2 = $("#doughnut-chartcanvas-2");
//doughnut chart data
var data1 = {
labels: ["match1", "match2", "match3", "match4", "match5"],
datasets: [
{
label: "TeamA Score",
data: [10, 50, 25, 70, 40],
backgroundColor: [
"#DEB887",
"#A9A9A9",
"#DC143C",
"#F4A460",
"#2E8B57"
],
borderColor: [
"#CDA776",
"#989898",
"#CB252B",
"#E39371",
"#1D7A46"
],
borderWidth: [1, 1, 1, 1, 1]
}
]
};
//doughnut chart data
var data2 = {
labels: ["match1", "match2", "match3", "match4", "match5"],
datasets: [
{
label: "TeamB Score",
data: [20, 35, 40, 60, 50],
backgroundColor: [
"#FAEBD7",
"#DCDCDC",
"#E9967A",
"#F5DEB3",
"#9ACD32"
],
borderColor: [
"#E9DAC6",
"#CBCBCB",
"#D88569",
"#E4CDA2",
"#89BC21"
],
borderWidth: [1, 1, 1, 1, 1]
}
]
};
//options
var options = {
responsive: true,
title: {
display: true,
position: "top",
text: "Doughnut Chart",
fontSize: 18,
fontColor: "#111"
},
legend: {
display: true,
position: "bottom",
labels: {
fontColor: "#333",
fontSize: 16
}
}
};
//create Chart class object
var chart1 = new Chart(ctx1, {
type: "doughnut",
data: data1,
options: options
});
//create Chart class object
var chart2 = new Chart(ctx2, {
type: "doughnut",
data: data2,
options: options
});
});

