JavaScript

Drawing a line chart with Chart.js

A canvas, a dataset and a few lines of config — the fastest path to a clean line chart.

rc
Théo « rootcause »
dev web & performance · updated Jan 2025
This guide revisits and updates an original tutorial from noiretaya.com (log.noiretaya.com/238). The code has been refreshed for current versions.

Set up the canvas

Chart.js renders into a <canvas>. Add one to the page and load the library.

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

Create the chart

Pass labels (x axis) and one or more datasets. Each dataset is a series of values aligned to the labels.

const ctx = document.getElementById('chart');
new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Jan','Feb','Mar','Apr','May'],
    datasets: [{
      label: 'Visitors',
      data: [120, 190, 170, 250, 300],
      borderColor: '#c8102e',
      tension: 0.3,         // smooth the line
      fill: false
    }]
  },
  options: { responsive: true, plugins: { legend: { display: true } } }
});

Useful tweaks

  • tension between 0 and 0.4 softens the curve.
  • fill: true shades the area under the line.
  • Add a second object to datasets to overlay series.
Tip: keep data fetching separate from rendering — load your JSON, then call new Chart(); it makes the chart easy to refresh with chart.update().