Chart.js 是一个基于 HTML5 Canvas 的 JavaScript 图表库,可以用于创建各种交互式数据可视化。本文将介绍使用 npm 包 Chart.js 创建图表的步骤。
步骤 1:安装 Chart.js
首先,使用以下命令在您的项目中安装 Chart.js:
npm install chart.js --save
步骤 2:创建画布
在 HTML 页面中创建一个 <canvas> 标签,并指定它的 ID。例如:
<canvas id="myChart"></canvas>
步骤 3:引入 Chart.js
在你的 JavaScript 文件顶部添加以下代码来引入 Chart.js:
import Chart from 'chart.js';
步骤 4:创建图表对象
创建一个新的 Chart 对象并传递 canvas 元素的 ID 作为第一个参数,以及一个配置对象作为第二个参数。例如:
// www.javascriptcn.com code example
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
}
}
}
});步骤 5:展示图表
最后,您可以通过调用 myChart.update() 方法来更新图表数据,并且调用 myChart.destroy() 方法来销毁图表对象。
这是一个简单的例子,它将创建一个垂直条形图:
// www.javascriptcn.com code example
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)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});这将创建一个简单的水平条形图:
// www.javascriptcn.com code example
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'horizontalBar',
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)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
}]
},
options: {
scales: {
x: {
beginAtZero: true
}
}
}
});结论
通过
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/32203