← 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.

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.

Example: Setting Up Chart.js

javascript
<canvas id="myChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  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.

Example: Chart Types

javascript
<canvas id="myChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  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.

Example: Configuring Data and Datasets

javascript
<canvas id="myChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  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.

Example: 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.

Example: 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>
Common Mistakes
  1. Forgetting to include the Chart.js script itself before using the Chart constructor, causing a "Chart is not defined" error.
  2. Passing a canvas element's ID as a string when the API expects the element itself (or vice versa) -- Chart.js accepts either, but mixing them up in your own helper code can cause confusion.
  3. Not calling .destroy() on an existing chart instance before creating a new one on the same canvas, leaving overlapping or ghost charts behind.
Chapter Summary
  • new Chart(canvasElement, config) creates a chart, where config specifies the chart type, data, and options.
  • Chart.js supports many built-in chart types (bar, line, pie, doughnut, radar, and more) via the type field.
  • Updating a chart's data and calling .update() refreshes it with smooth transitions, without needing to recreate the whole chart.
Browser Support

Chart.js works in every modern browser supporting Canvas, which is effectively universal among current browsers.

🔒

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.