Create a Bar Chart with HTML Canvas and JavaScript

A Canvas bar chart can be built from a JavaScript data array by scaling each value to the chart's drawing height and using fillRect() for the bars. Keep the source data available as HTML as well, because Canvas pixels are not exposed like semantic table content.

Bar chart geometry showing Canvas bar positions and dimensions

Data for the bar chart Top ↑

const data = [
  ['Class-5', 140],
  ['Class-4', 150],
  ['Class-3', 170],
  ['Class-2', 110],
  ['Class-1', 170]
];

Working responsive bar chart Top ↑

Bar chart of student totals by class.
Student totals used in the Canvas bar chart
ClassStudents
Class-5140
Class-4150
Class-3170
Class-2110
Class-1170

Scale data to the chart area Top ↑

Do not assume one data unit equals one Canvas pixel. Find the maximum value and calculate a scale so the chart adapts to the available plot height.

const maxValue = Math.max(...data.map(item => item[1]));
const plotHeight = canvas.height - topPadding - bottomPadding;
const barHeight = value / maxValue * plotHeight;
const y = topPadding + plotHeight - barHeight;
ctx.fillRect(x, y, barWidth, barHeight);

Draw labels and values Top ↑

Use fillText() after setting font and textAlign. Keep labels outside shadow state unless the shadow is genuinely useful.

ctx.font = '14px sans-serif';
ctx.textAlign = 'center';
ctx.fillText(label, barX + barWidth / 2, baselineY + 24);
ctx.fillText(String(value), barX + barWidth / 2, barY - 7);

Canvas bitmap size vs CSS size Top ↑

Set the Canvas width and height attributes for the drawing coordinate space. CSS can make the element responsive, but if the display size differs from the bitmap size, the browser scales the finished pixels.

Accessible chart data Top ↑

Do not make Canvas the only representation of important data. A nearby HTML table, summary, or other semantic equivalent lets users access the values without interpreting pixels.

Frequently asked questions Top ↑

How do I make bar heights fit the Canvas? Top ↑

Scale each value relative to the maximum value and the available plot height.

Why is Canvas y calculated from the bottom for a bar chart? Top ↑

Canvas y increases downward, so an upright bar starts at baselineY minus its calculated height.

Can fillRect() draw each bar? Top ↑

Yes. fillRect() is a simple and efficient method for rectangular bars.

Should bar chart data also be in HTML? Top ↑

Yes when the data is meaningful. Canvas alone is not a semantic data representation.

How do I create grouped or stacked bars? Top ↑

See the existing stacked/grouped bar graph tutorial and extend the data model to include multiple series.

fillRect() | fillText() | Stacked/grouped bar graph | Pie chart | Canvas tutorial





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