Chart.js – JavaScript Chart Library
Chart.js is a simple and flexible JavaScript library for creating charts using the HTML5 <canvas>
element. It supports line, bar, pie, radar, doughnut, polar area, bubble, and scatter charts with animations and responsive design.
Getting Started
1. Include Chart.js
You can include it via CDN:
<script src="<https://cdn.jsdelivr.net/npm/chart.js>"></script>
Or install via npm for projects:
npm install chart.js
2. HTML Canvas Element
All charts are drawn on a <canvas>
:
<canvas id="myChart" width="400" height="200"></canvas>
Creating a Chart
Example: Line Chart
<script>
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'line', // Chart type
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [{
label: 'Sales',
data: [12, 19, 3, 5, 2],
borderColor: 'blue',
backgroundColor: 'rgba(0,0,255,0.1)',
fill: true
}]
},
options: {
responsive: true,
plugins: {
legend: {
display: true
},
title: {
display: true,
text: 'Monthly Sales Data'
}
},
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>
Supported Chart Types
Type | Description |
---|---|
Line | Show trends over time |
Bar | Compare data across categories |
Pie | Display percentages of a whole |
Doughnut | Similar to pie with a center hole |
Radar | Compare multiple variables visually |
Polar Area | Like pie, shows relative data sizes |
Bubble | Scatter chart with varying bubble sizes |
Scatter | Plot x and y coordinates |
Customizing Charts
Colors
borderColor: 'red',
backgroundColor: 'rgba(255,0,0,0.2)'
Tooltips
options: {
plugins: {
tooltip: {
enabled: true
}
}
}
Animations
options: {
animation: {
duration: 1000,
easing: 'easeOutBounce'
}
}
Legends
options: {
plugins: {
legend: {
display: true,
position: 'top'
}
}
}
Updating Charts Dynamically
You can update chart data on the fly:
myChart.data.datasets[0].data = [5, 10, 15, 20, 25];
myChart.update();
Advantages of Chart.js
- Lightweight and easy to use
- Supports responsive design and animations
- Works well for small to medium data sets
- Open-source and actively maintained
When to Use Chart.js
- Simple dashboards
- Quick visualizations for websites
- Projects where ease of use and visual appeal are more important than deep customization