How to use Chart.js
Ordinary Coders
Posted on March 30, 2021
1) Chart.js Installation - How to install Chart.js
Install Chart.js via npm or bower.
Or use the CDN to added the minified Chart.js scripts.
Chart.js npm
How to install Chart.js with npm
npm install chart.js --save
Install chart.js in the command prompt using npm.
Chart.js Bower
How to install Chart.js with bower
bower install chart.js --save
Or install Chart.js in the command prompt using bower.
Chart.js CDN
How to use the Chart.js CDN
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
<!--Chart.js JS CDN-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
</head>
<body>
...
</body>
</html>
While the documentation recommends installing Chart.js in the command prompt, add the Chart.js CDN to the <head>
element for light-weight development.
The examples below use the CDN.
2) Integration - How to add Chart.js to an HTML document
Chart.js requires HTML and JavaScript code.
The HTML code places the chart in the document using the <canvas>
element while the JavaScript function instantiates the chart.
How to add the Chart.js element
How to display Chart.js in an HTML template
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chart.js Integration</title>
<!--Chart.js JS CDN-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
</head>
<body>
<div>
<canvas id="myChart"></canvas>
</div>
</body>
</html>
Chart.js requires a <canvas>
element containing the unique id of the chart for the data to render in the HTML template.
This is the only HTML code required.
How to instantiate Chart.js
How to add the Chart.js JavaScript function
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chart.js Integration</title>
<!--Chart.js JS CDN-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
</head>
<body>
<div>
<canvas id="myChart"></canvas>
</div>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
});
</script>
</body>
</html>
Then create the script that creates the chart.
The type, data, and configuration options will be added within the function.
Posted on March 30, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.