A Canvas pie chart converts each data value into a fraction of a full circle. For every segment, calculate value / total * 2 * Math.PI, draw an arc, fill the slice, then advance the start angle.
const data = [
[40, 'Available', '#2e7d32'],
[15, 'Blocked', '#e0b400'],
[20, 'Sold', '#c62828']
];
| Status | Value |
|---|---|
| Available | 40 |
| Blocked | 15 |
| Sold | 20 |
const total = data.reduce((sum, item) => sum + item[0], 0);
const sliceAngle = value / total * 2 * Math.PI;
const endAngle = startAngle + sliceAngle;
A full circle is 2 * Math.PI radians. There is no need to round each segment angle before drawing; rounding intermediate values can accumulate visible error.
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, radius, startAngle, endAngle);
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
startAngle = endAngle;
The midpoint angle of a slice is useful for label positioning. Math.cos() gives the x component and Math.sin() gives the y component.
const mid = startAngle + sliceAngle / 2;
const labelX = centerX + Math.cos(mid) * (radius + 30);
const labelY = centerY + Math.sin(mid) * (radius + 30);
For number formatting, see JavaScript toFixed().
Color wedges alone are not a complete accessible representation. Include visible labels and preserve the source values in semantic HTML, such as the table above. Avoid relying on color alone to identify categories.
Divide the slice value by the total and multiply by 2 × Math.PI.
No. Keep full numeric precision for geometry and round only text shown to users.
It creates the radial side from the center so the arc becomes a wedge when the path is closed.
Use -Math.PI / 2 as the initial start angle.
Yes when the chart carries meaningful data. A table or text summary provides semantic access to the values.
arc() | Bar chart | toFixed() | 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.