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.
const data = [
['Class-5', 140],
['Class-4', 150],
['Class-3', 170],
['Class-2', 110],
['Class-1', 170]
];
| Class | Students |
|---|---|
| Class-5 | 140 |
| Class-4 | 150 |
| Class-3 | 170 |
| Class-2 | 110 |
| Class-1 | 170 |
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);
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);
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.
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.
Scale each value relative to the maximum value and the available plot height.
Canvas y increases downward, so an upright bar starts at baselineY minus its calculated height.
Yes. fillRect() is a simple and efficient method for rectangular bars.
Yes when the data is meaningful. Canvas alone is not a semantic data representation.
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
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.