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.
const data = [120, 310, 450, 300, 200, 440, 500];
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.
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.
For meaningful charts, provide the same values as an HTML list or table and use labels that do not depend on color alone.
Because Canvas y coordinates increase downward.
No. One 2D context can draw axes, grid lines, and the data series.
Yes, but calculate a zero baseline between the minimum and maximum.
Use Bézier curves if smoothing is appropriate, but do not distort the underlying data.
No. Setting width or height clears the Canvas and resets its drawing state.
Stacked bar chart | Pie chart | Canvas reference
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.