Create a Pie Chart with HTML Canvas and JavaScript

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.

Canvas arc showing start and end angles used for pie chart slices

Pie chart data Top ↑

const data = [
  [40, 'Available', '#2e7d32'],
  [15, 'Blocked', '#e0b400'],
  [20, 'Sold', '#c62828']
];

Working pie chart Top ↑

Pie chart showing available, blocked and sold values.
Values used in the Canvas pie chart
StatusValue
Available40
Blocked15
Sold20

Convert values to radians Top ↑

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.

Draw each pie slice Top ↑

ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, radius, startAngle, endAngle);
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
startAngle = endAngle;

Position labels around the circle Top ↑

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);
Coordinates around a circle for Canvas arc labels

For number formatting, see JavaScript toFixed().

Accessible pie-chart data Top ↑

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.

Frequently asked questions Top ↑

How is a pie-chart angle calculated? Top ↑

Divide the slice value by the total and multiply by 2 × Math.PI.

Should I call toFixed() before drawing each angle? Top ↑

No. Keep full numeric precision for geometry and round only text shown to users.

Why call moveTo(centerX, centerY)? Top ↑

It creates the radial side from the center so the arc becomes a wedge when the path is closed.

How do I start the first slice at the top? Top ↑

Use -Math.PI / 2 as the initial start angle.

Should Canvas pie-chart values also be available in HTML? Top ↑

Yes when the chart carries meaningful data. A table or text summary provides semantic access to the values.

arc() | Bar chart | toFixed() | 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