Chart.js Basics — Setup, Configuration & Your First Chart
Chart.js is a free, open-source JavaScript library that turns data into beautiful, animated HTML5 charts with just a few lines of code. It wraps the HTML5 Canvas API with a clean configuration-based API so you don’t need to draw a single pixel yourself.
What You’ll Learn
By the end of this tutorial, you’ll install Chart.js via CDN and npm, understand the chart configuration object (type, data, options), create bar, line, pie, and other chart types, set up the canvas element correctly, update charts dynamically with new data, and avoid common pitfalls like memory leaks and canvas sizing issues.
Why Chart.js Matters
Data is easier to understand when you can see it. A spreadsheet of 1000 sales numbers tells you nothing at a glance. A bar chart of the same data shows you trends, outliers, and patterns instantly.
Chart.js makes this trivially easy. Unlike D3.js which requires 30+ lines for a basic chart, Chart.js needs just 5 lines. It handles axes, legends, tooltips, animations, and responsive sizing automatically.
Real-world use: Durga Antivirus Pro uses Chart.js for its real-time threat dashboard. A line chart shows detected threats per minute over the last 24 hours. A doughnut chart breaks down threats by type (malware, phishing, ransomware). Both update live as new telemetry arrives, with smooth animations that draw attention to spikes.
Where This Fits in Your Learning Path
flowchart LR
A["HTML, CSS & JavaScript Basics"] --> B["**Chart.js Basics**"]
B --> C["Line, Bar & Mixed Charts"]
C --> D["Pie, Doughnut, Radar & Polar"]
D --> E["Scatter & Bubble Charts"]
E --> F["Chart.js Advanced"]
style B fill:#f97316,stroke:#c2410c,color:#fff
style A fill:#e5e7eb,stroke:#9ca3af,color:#374151
style F fill:#22c55e,stroke:#16a34a,color:#22c55e
Chart.js vs D3.js — Which One Should You Use?
Before diving in, it helps to understand where Chart.js fits in the data visualization landscape:
| Chart.js | D3.js |
|---|---|
| High-level API — 5 lines = chart | Low-level API — 30+ lines for a chart |
| Canvas-based rendering | SVG-based rendering |
| Built-in animations and transitions | Manual animations |
| Limited customization | Total control over every pixel |
| Best for: standard charts, dashboards | Best for: custom visualizations, interactive data art |
When to choose Chart.js: You need a bar chart, line chart, pie chart, or any standard chart type, and you want it working in minutes. This covers 90% of real-world charting needs.
When to choose D3.js: You need a completely custom visualization — a chord diagram, a force-directed graph, a geographic map with custom projections.
Installation
CDN (Easiest Way to Start)
Add a single <script> tag:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>This loads the latest version and registers Chart as a global variable.
Specific Version
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"></script>npm (For Build Systems)
npm install chart.jsimport { Chart, registerables } from 'chart.js'
Chart.register(...registerables)Your First Chart
Let’s create a bar chart showing color preference votes. This is the “Hello, World!” of Chart.js:
<!DOCTYPE html>
<html>
<head>
<title>My First Chart</title>
</head>
<body>
<div style="width: 500px;">
<canvas id="myChart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('myChart').getContext('2d')
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
}]
},
options: {
scales: {
y: { beginAtZero: true }
}
}
})
</script>
</body>
</html>What’s happening step by step:
- An HTML
<canvas>element provides the drawing surface getContext('2d')gets the 2D rendering contextnew Chart(ctx, config)creates a chart on that canvas- The
configobject has three parts:type(what kind of chart),data(what to visualize), andoptions(how it looks)
The Chart Configuration Object
Every Chart.js chart uses the same three-part structure:
new Chart(ctx, {
type: 'bar', // Chart type
data: { // What data to show
labels: [...],
datasets: [...]
},
options: { // How it looks and behaves
responsive: true,
plugins: {...},
scales: {...}
}
})Chart Types
| Type | Description |
|---|---|
'bar' | Vertical or horizontal bars |
'line' | Connected points with optional fill |
'radar' | Spider/radar chart |
'pie' | Circular proportional slices |
'doughnut' | Donut chart with a hole |
'polarArea' | Polar area with equal angles |
'bubble' | Three-variable bubbles (x, y, r) |
'scatter' | X/Y scatter plot |
Data Structure
The data object has two parts:
data: {
labels: ['January', 'February', 'March', 'April'],
datasets: [
{
label: 'Sales 2024',
data: [65, 59, 80, 81],
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
},
{
label: 'Sales 2023',
data: [45, 49, 60, 71],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
}
]
}Labels are the x-axis categories. Datasets are the series of data. Each dataset can have its own styling.
Important: The labels array and each data array must have the same length. Chart.js silently drops extra items if they don’t match.
Canvas Setup Best Practices
Controlling Chart Size
Don’t set width and height attributes on the <canvas> element directly. Instead, wrap it in a container and let Chart.js handle the sizing:
<!-- Good: container controls size -->
<div style="position: relative; width: 80vw; max-width: 800px; height: 400px;">
<canvas id="chart"></canvas>
</div>
<!-- Good: responsive with aspect ratio -->
<div style="width: 100%; max-width: 600px;">
<canvas id="chart2"></canvas>
</div>Destroying Charts to Prevent Memory Leaks
If you recreate a chart on the same canvas (e.g., when switching datasets), always destroy the old one first:
let myChart = null
function createChart(config) {
if (myChart) myChart.destroy()
myChart = new Chart(document.getElementById('chart'), config)
}Creating a second chart on a canvas that already has one throws an error.
Updating Charts Dynamically
Real-world charts don’t sit still. Data changes, and the chart needs to update:
// Update existing data
chart.data.datasets[0].data = [10, 20, 30]
chart.data.labels = ['A', 'B', 'C']
chart.update() // Animate the transition
// Update without animation
chart.update('none')
// Add a data point
chart.data.labels.push('D')
chart.data.datasets[0].data.push(40)
chart.update()
// Remove the first data point
chart.data.labels.shift()
chart.data.datasets[0].data.shift()
chart.update()
// Reset to original state
chart.reset()Why chart.update() is important: It animates the transition smoothly. Without calling it, the chart doesn’t know the data changed.
Common Mistakes Beginners Make
1. Creating Multiple Charts on the Same Canvas
Creating new Chart(ctx) on a canvas that already has a chart throws an error. Always call chart.destroy() first.
2. Canvas Container Has Zero Size
If the container has no explicit dimensions (or has display: none) when the chart initializes, the chart won’t display. Ensure the container has width and height or use responsive: true with a container that has layout.
3. Mismatched Labels and Data Array Lengths
// Wrong: 4 labels, 3 data points
labels: ['A', 'B', 'C', 'D']
data: [10, 20, 30] // D gets no value
Chart.js won’t warn you — it just renders empty space for the missing data point.
4. Forgetting getContext('2d')
Passing a canvas element directly to new Chart() works, but passing document.getElementById('chart') is required. Don’t pass a jQuery object or class selector.
5. Creating Charts Inside a Loop Without Destroying
Rapidly creating new Chart() instances in a loop causes memory growth. Reuse a single instance or destroy before recreating.
Practice Questions
What three parts does every Chart.js configuration object have?
type(chart type),data(labels + datasets), andoptions(styling and behavior).Why should you call
chart.destroy()before creating a new chart on the same canvas? To prevent the “Canvas already has a chart” error and avoid memory leaks from orphaned chart instances.How do you update a chart’s data and animate the transition? Modify the
chart.dataarrays and callchart.update(). Chart.js animates the transition automatically.What happens if your labels array has 5 items but your data array has 3 items? Chart.js renders 3 data points with 3 labels. The extra 2 labels have no corresponding bars/points.
How does Chart.js differ from D3.js in terms of API level? Chart.js is high-level (5 lines for a chart, built-in animations). D3.js is low-level (30+ lines, manual control over every element).
Challenge
Build a live updating chart dashboard with:
- A bar chart showing weekly sales data
- Buttons to add a data point, remove the last point, randomize all data, and reset to original
- Each action triggers
chart.update()with smooth animation - The chart title updates to show how many data points are currently displayed
FAQ
Try It Yourself: Live Updating Chart
Experiment with adding, removing, and randomizing data points to see chart transitions in action.
<!DOCTYPE html>
<html>
<head>
<title>Live Updating Chart</title>
<style>
body { font-family: sans-serif; padding: 20px; }
.chart-box { width: 600px; max-width: 100%; margin: 20px 0; }
.controls { display: flex; gap: 10px; flex-wrap: wrap; }
.controls button { padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer; background: #4CAF50; color: white; font-size: 14px; }
.controls button.remove { background: #f44336; }
.controls button.randomize { background: #FF9800; }
</style>
</head>
<body>
<h2>Live Updating Chart</h2>
<div class="chart-box"><canvas id="liveChart"></canvas></div>
<div class="controls">
<button onclick="addData()">Add Data Point</button>
<button onclick="removeData()" class="remove">Remove Last</button>
<button onclick="randomize()" class="randomize">Randomize</button>
<button onclick="resetData()">Reset</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('liveChart').getContext('2d')
const chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [{
label: 'Monthly Value',
data: [65, 59, 80, 81, 56],
borderColor: 'rgba(54, 162, 235, 1)',
backgroundColor: 'rgba(54, 162, 235, 0.1)',
fill: true, tension: 0.4, pointRadius: 5, pointHoverRadius: 8
}]
},
options: {
responsive: true,
plugins: { title: { display: true, text: 'Live Data Demo' }, legend: { display: false } },
scales: { y: { beginAtZero: true } }
}
})
function addData() {
chart.data.labels.push('M' + (chart.data.labels.length + 1))
chart.data.datasets[0].data.push(Math.floor(Math.random() * 100) + 10)
chart.update()
}
function removeData() { if (chart.data.labels.length > 1) { chart.data.labels.pop(); chart.data.datasets[0].data.pop(); chart.update() } }
function randomize() { chart.data.datasets[0].data = chart.data.datasets[0].data.map(() => Math.floor(Math.random() * 100) + 10); chart.update() }
function resetData() { chart.data.labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May']; chart.data.datasets[0].data = [65, 59, 80, 81, 56]; chart.update() }
</script>
</body>
</html>What to expect: A line chart with animated transitions. Click “Add Data Point” to extend the chart, “Randomize” to see smooth data transitions, and “Reset” to return to the original data.
What’s Next
| Tutorial | What You’ll Learn |
|---|---|
| Line, Bar & Mixed Charts | Multi-series, stacked bars, mixed chart types |
| Pie, Doughnut, Radar & Polar | Circular charts, radar comparisons |
Related topics: JavaScript arrays and objects, HTML Canvas.
What’s Next
Congratulations on completing this Chartjs Basics tutorial! Here’s where to go from here:
- Practice daily — Consistency is more important than long study sessions
- Build a project — Apply what you learned by building something real
- Explore related topics — Check out other tutorials in the same category
- Join the community — Discuss with other learners and share your progress
Remember: every expert was once a beginner. Keep coding!
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro