J

JavaScript Handbook

Clean • Professional

Chart.js in JavaScript

2 minute

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

TypeDescription
LineShow trends over time
BarCompare data across categories
PieDisplay percentages of a whole
DoughnutSimilar to pie with a center hole
RadarCompare multiple variables visually
Polar AreaLike pie, shows relative data sizes
BubbleScatter chart with varying bubble sizes
ScatterPlot 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

Article 0 of 0