Stacked Bar Chart with HTML Canvas and JavaScript

A stacked or progress-style bar chart can show two related values in one bar. In this example, each class has a total number of students and a passed count. The outlined bar represents the total; the filled bar represents the passed count.

Your browser does not support Canvas.
Data used in the stacked Canvas chart
ClassTotalPassed
Class-5140100
Class-4150130
Class-3170100
Class-211060
Class-117085

Store both values in one data array Top ↑

const data = [
  ['Class-5', 140, 100],
  ['Class-4', 150, 130]
];

Scale values to the chart height Top ↑

const maxValue = Math.max(...data.map(row => row[1]));
const scale = plotHeight / maxValue;
const totalHeight = total * scale;
const passedHeight = passed * scale;

Scaling makes the chart independent of the raw value units. The original tutorial used pixel heights directly; that works only when data values conveniently fit the Canvas.

Draw the total and filled portions Top ↑

ctx.strokeRect(x, baseline - totalHeight, barWidth, totalHeight);
ctx.fillRect(x, baseline - passedHeight, barWidth, passedHeight);

See the basic bar chart and fillRect() for the underlying rectangle logic.

Accessibility Top ↑

Keep the source values in a table or text summary so the chart is not the only representation of the data.

Frequently asked questions Top ↑

Is this a true stacked chart?

It is a nested/progress-style comparison: the passed value is drawn inside the total. A conventional stacked chart would place categories end-to-end.

Why scale the values?

Scaling maps arbitrary data values to available Canvas pixels.

Can more than two values be stacked?

Yes. Track the cumulative height of each segment.

Can the bars be horizontal?

Yes. Swap the value mapping from height to width.

Should labels be drawn only on Canvas?

No. Important values should also be available in semantic HTML.

Basic bar chart | Line graph | Canvas clock | 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