Line Chart with HTML Canvas and JavaScript

A Canvas line chart plots data values as points and connects them with line segments. The essential steps are to choose the chart area, scale each value to pixels, draw axes, then use moveTo() and lineTo() for the series.

Example of a line graph drawn on HTML Canvas
Your browser does not support Canvas.

Start with a JavaScript data array Top ↑

const data = [120, 310, 450, 300, 200, 440, 500];

Scale data to Canvas coordinates Top ↑

const maxValue = Math.ceil(Math.max(...data) / 100) * 100;
const y = top + plotHeight - (value / maxValue) * plotHeight;

Canvas y coordinates increase downward, so chart values normally subtract their scaled height from the bottom of the plotting area.

Connect the points Top ↑

ctx.beginPath();
data.forEach((value, index) => {
  const x = left + index * xGap;
  const y = top + plotHeight - (value / maxValue) * plotHeight;
  if (index === 0) ctx.moveTo(x, y);
  else ctx.lineTo(x, y);
});
ctx.stroke();

See lineTo() for path basics.

Accessibility Top ↑

For meaningful charts, provide the same values as an HTML list or table and use labels that do not depend on color alone.

Frequently asked questions Top ↑

Why does the y formula subtract the value?

Because Canvas y coordinates increase downward.

Do I need two Canvas contexts?

No. One 2D context can draw axes, grid lines, and the data series.

Can I plot negative values?

Yes, but calculate a zero baseline between the minimum and maximum.

How do I make the line smoother?

Use Bézier curves if smoothing is appropriate, but do not distort the underlying data.

Should Canvas width be changed after drawing?

No. Setting width or height clears the Canvas and resets its drawing state.

Stacked bar chart | Pie chart | Canvas reference





plus2net.com










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer