Chart.js Fundamentals
You'll learn how to set up Chart.js and create basic canvas-based charts with minimal configuration.
What Is Chart.js?
Chart.js is a lightweight, canvas-based charting library that prioritizes simplicity over flexibility. Unlike D3.js, which gives you complete control over every visual element, Chart.js provides pre-built chart types that "just work" with sensible defaults. Think of it as a menu at a restaurant (Chart.js) versus a full kitchen (D3.js)—sometimes you just want to order a dish, not cook from scratch.
Basic Setup
First, include Chart.js via CDN or npm. You need a <canvas> element as your container:
<canvas id="myChart"></canvas>
Then create a chart instance in JavaScript:
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [{
label: 'Votes',
data: [12, 19, 3]
}]
}
});
Core Chart Types
Chart.js includes built-in types: 'bar', 'line', 'pie', 'doughnut', 'radar', 'polarArea', and 'scatter'. Just change the type property to switch between them.
Essential Configuration
Control appearance through the options object:
options: {
responsive: true,
plugins: {
legend: {
display: true,
position: 'top'
}
},
scales: {
y: {
beginAtZero: true
}
}
}
Chart.js handles canvas rendering, animations, and responsiveness automatically—you focus on data, not drawing primitives.
Key Takeaway: Chart.js provides a quick, declarative way to create common chart types on canvas with minimal code, trading D3's flexibility for ease of use and speed of implementation.