JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Chart.js


Chart.js is one of the most popular JavaScript libraries used to create simple, clean, and responsive charts for web applications. It is widely used because it is lightweight, easy to learn, and produces visually appealing charts with minimal code. If you are building dashboards, admin panels, reports, or analytics pages, Chart.js is an excellent choice.

In this tutorial, you will learn what Chart.js is, why it is used, how it works internally, how to include it in your project, and how to create different types of charts step by step using JavaScript. This chapter is written in a beginner friendly yet professional way, so you can confidently use Chart.js in real projects.

What Is Chart.js

Chart.js is an open source JavaScript library that allows you to draw charts using the HTML canvas element. It supports many common chart types and provides built-in animations, tooltips, legends, and responsiveness.

Chart.js is mainly focused on simplicity. You do not need complex configuration to get started. With just a canvas element and a small JavaScript object, you can generate professional charts.

Why Use Chart.js

Chart.js is preferred by many developers for several reasons.

It is lightweight and fast, making it suitable even for small projects.
It produces responsive charts that automatically adjust to screen size.
It supports animations and hover effects by default.
It has clean documentation and a gentle learning curve.
It works well with modern JavaScript frameworks and plain JavaScript.

Because of these benefits, Chart.js is commonly used in admin dashboards, student portals, analytics panels, and reporting tools.

Chart Types Supported by Chart.js

Chart.js supports many chart types that cover most real world use cases.

Some commonly used chart types are:

  • Line chart

  • Bar chart

  • Pie chart

  • Doughnut chart

  • Radar chart

  • Polar area chart

  • Scatter chart

  • Bubble chart

Each chart type is designed to represent data clearly and effectively.

How Chart.js Works

Chart.js works using the HTML canvas element. The library draws charts directly onto the canvas using JavaScript.

The basic flow is simple:

You create a canvas element in HTML.
You define data and configuration in JavaScript.
Chart.js renders the chart inside the canvas.

The chart is controlled through a configuration object that includes data, options, and chart type.

Adding Chart.js to Your Project

The easiest way to use Chart.js is through a CDN.

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

You also need a canvas element where the chart will be displayed.

<canvas id="myChart" width="400" height="200"></canvas>

The canvas acts as the drawing surface for Chart.js.

Creating Your First Chart

Let us create a simple bar chart.

const ctx = document.getElementById("myChart");

new Chart(ctx, {
    type: "bar",
    data: {
        labels: ["January", "February", "March", "April"],
        datasets: [{
            label: "Monthly Sales",
            data: [30, 45, 28, 60],
            backgroundColor: "rgba(54, 162, 235, 0.6)"
        }]
    }
});

This code creates a bar chart with labels on the x-axis and values on the y-axis. Chart.js automatically adds animations and hover effects.

Understanding the Chart Configuration

The chart configuration has three main parts.

Type defines the chart type such as bar or line.
Data contains labels and datasets.
Options control appearance and behavior.

Understanding this structure is key to using Chart.js effectively.

Working with Datasets

A dataset represents one set of values in a chart.

datasets: [{
    label: "Attendance",
    data: [85, 90, 88, 92],
    borderColor: "green",
    backgroundColor: "rgba(0, 128, 0, 0.2)"
}]

You can add multiple datasets to compare data visually.

Line Chart Example

Line charts are commonly used to show trends.

new Chart(ctx, {
    type: "line",
    data: {
        labels: ["Week 1", "Week 2", "Week 3", "Week 4"],
        datasets: [{
            label: "Website Visits",
            data: [120, 190, 300, 250],
            borderColor: "blue",
            fill: false
        }]
    }
});

Line charts are ideal for time based data.

Pie and Doughnut Charts

Pie and doughnut charts show proportions.

new Chart(ctx, {
    type: "pie",
    data: {
        labels: ["Chrome", "Firefox", "Edge", "Safari"],
        datasets: [{
            data: [55, 20, 15, 10],
            backgroundColor: ["red", "orange", "blue", "green"]
        }]
    }
});

These charts are useful when you want to show percentage distribution.

Chart Options and Customization

Chart.js allows deep customization through options.

options: {
    responsive: true,
    plugins: {
        legend: {
            position: "top"
        },
        title: {
            display: true,
            text: "User Statistics"
        }
    }
}

Using options, you can control legends, titles, tooltips, scales, and animations.

Working with Axes

Axes can be customized for better readability.

options: {
    scales: {
        y: {
            beginAtZero: true
        }
    }
}

This ensures the y-axis starts from zero.

Responsive Charts

Chart.js charts are responsive by default. They adjust automatically based on screen size.

This makes them suitable for mobile friendly applications without extra effort.

Updating Chart Data Dynamically

Charts can be updated when data changes.

chart.data.datasets[0].data.push(70);
chart.update();

This is useful for live dashboards and admin panels.

Common Mistakes to Avoid

Many beginners face similar issues.

Forgetting to include the Chart.js script.
Using incorrect canvas id.
Passing data in wrong format.
Overloading charts with too many datasets.

Understanding the basics helps prevent these errors.

Best Practices

Use appropriate chart types for your data.
Keep labels short and clear.
Avoid unnecessary colors.
Do not overload charts with excessive data.
Test charts on different screen sizes.

Good charts focus on clarity rather than decoration.

Real World Use Cases

Chart.js is commonly used in:

Student performance dashboards
Sales and revenue reports
Website analytics panels
Admin dashboards
Survey result visualization

Its simplicity makes it ideal for both small and large projects.

Chart.js vs Other Chart Libraries

Compared to heavier libraries, Chart.js is easier to set up and faster to implement. While it may not offer extremely advanced charts like some libraries, it covers most practical needs efficiently.

Summary of JS Chart.js

Chart.js is a powerful yet simple JavaScript library for creating responsive and interactive charts. It uses the HTML canvas element and provides built-in animations, tooltips, and customization options. With support for multiple chart types and easy configuration, Chart.js is perfect for dashboards, reports, and analytics features. By mastering its data structure, options, and update methods, you can build clean, professional charts that make data easy to understand and visually appealing.


Practice Questions

  1. Create a basic line chart showing monthly revenue for 6 months with smooth curves and markers.

  2. Create a bar chart comparing the sales of 5 different products. Customize each bar with a different color.

  3. Build a pie chart representing the percentage distribution of traffic sources (Direct, Organic, Referral).

  4. Create a doughnut chart with at least 4 segments showing different expense categories.

  5. Make a scatter chart with 10 random data points. Customize marker size and color.

  6. Create a stacked bar chart showing two datasets (e.g., Product A and Product B sales) across 6 months.

  7. Animate a line chart so that the data points appear gradually when the chart loads.

  8. Dynamically update a chart’s data and labels when a new dataset is added using chart.update().

  9. Create a radar chart comparing the performance of 3 students across 5 subjects.

  10. Implement tooltips and hover effects on a bar chart that display the exact value and category for each bar.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top