← Back to JavaScript Course | Chapter 10: DOM Advanced | Lesson 8 of 8

JS Chart.js

Chart.js is a popular, free JavaScript charting library built on top of canvas, handling the common chart types -- bar, line, pie, doughnut, radar -- along with axes, legends, tooltips, and animations, all through a single configuration object instead of manual drawing code.
Syntax
javascript
new Chart(canvasElement, {
  type: "bar",
  data: { labels: [], datasets: [{ data: [] }] },
  options: {}
});

Setting Up Chart.js

Chart.js is included via a <script> tag (from a CDN or a local copy), after which the global Chart constructor becomes available -- new Chart(canvasElement, config) then creates and renders a chart onto that canvas immediately.

Note: Include the Chart.js script tag before your own script that uses the Chart constructor, or it will not be defined yet when your code runs.
Warning: Chart.js requires a real canvas element to render into -- passing a div or other non-canvas element will fail.

उदाहरण: Setting Up Chart.js

javascript
<canvas id="myChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  // Draw a bar chart into the canvas, with two bars labeled "A" and "B"
  new Chart(document.getElementById("myChart"), {
    type: "bar",
    data: { labels: ["A", "B"], datasets: [{ data: [10, 20] }] },
  });
</script>

Chart Types

The type field in the configuration object selects the chart style -- "bar" for bar charts, "line" for line graphs, "pie" and "doughnut" for proportion charts, "radar" for multi-axis comparisons -- with the same data/options structure adapting to each.

Note: Try changing only the type field on an existing configuration to quickly compare how the same data looks in different chart styles.
Warning: Not every chart type suits every kind of data -- a pie chart works well for parts of a whole, but poorly for a trend over time, which a line chart handles better.

उदाहरण: Chart Types

javascript
<canvas id="myChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  // Draw a pie chart into the canvas, split between "Yes" and "No"
  new Chart(document.getElementById("myChart"), {
    type: "pie",
    data: { labels: ["Yes", "No"], datasets: [{ data: [70, 30] }] },
  });
</script>

Configuring Data and Datasets

The data object holds labels (the categories shown along an axis or in a legend) and one or more datasets, each with its own values and visual styling (like backgroundColor) -- multiple datasets on one chart let you compare several data series at once.

Note: Give each dataset a clear label and distinct color when displaying more than one on the same chart, so the legend clearly distinguishes them.
Warning: The number of values in each dataset's data array must match the number of labels -- a mismatch produces a chart with missing or misaligned bars.

उदाहरण: Configuring Data and Datasets

javascript
<canvas id="myChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  // Draw a bar chart comparing two datasets (2023 vs 2024) across Jan/Feb
  new Chart(document.getElementById("myChart"), {
    type: "bar",
    data: {
      labels: ["Jan", "Feb"],
      datasets: [
        { label: "2023", data: [10, 20], backgroundColor: "blue" },
        { label: "2024", data: [15, 25], backgroundColor: "green" },
      ],
    },
  });
</script>

Updating a Chart Dynamically

A chart instance's .data property can be modified directly (like reassigning a dataset's data array), and calling .update() on the chart afterward redraws it with an animated transition to the new values, without needing to destroy and recreate the entire chart.

Note: Modify the existing chart instance's data and call .update() for live-updating dashboards, rather than tearing down and rebuilding the chart on every refresh.
Warning: Forgetting to call .update() after changing a chart's data leaves the visual display unchanged until something else triggers a redraw.

उदाहरण: Updating a Chart Dynamically

javascript
<canvas id="myChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  const chart = new Chart(document.getElementById("myChart"), {
    type: "bar",
    data: { labels: ["A", "B"], datasets: [{ data: [10, 20] }] },
  });
  chart.data.datasets[0].data = [30, 5];
  chart.update(); // animated transition to new values
</script>

Destroying a Chart Before Recreating It

Attempting to create a second Chart instance on the same canvas without first destroying the original produces overlapping or broken rendering -- calling .destroy() on the existing chart instance cleans it up properly before a new one is created.

Note: Store a reference to each Chart instance so you can call .destroy() on it later, especially in any code path that might recreate a chart on the same canvas.
Warning: Creating a new chart on a canvas that already has an active Chart instance, without destroying the old one first, is a very common source of "my chart looks broken" bugs.

उदाहरण: Destroying a Chart Before Recreating It

javascript
<canvas id="myChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  let chart = new Chart(document.getElementById("myChart"), {
    type: "bar",
    data: { labels: ["A"], datasets: [{ data: [5] }] },
  });
  chart.destroy(); // clean up before recreating
  chart = new Chart(document.getElementById("myChart"), {
    type: "line",
    data: { labels: ["A"], datasets: [{ data: [10] }] },
  });
</script>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.