An HTML Canvas dial or gauge converts a numeric value into an angle on a semicircle. Set a maximum value, map the current value to 0–180 degrees, draw the colored arc, and then rotate the pointer to the calculated position.
const maxData = 600;
const value = 500;
const angle = Math.PI + (value / maxData) * Math.PI;
The first Math.PI places the pointer at the left side of the semicircle. The fraction value / maxData then moves it across another π radians to the right side.
const gradient = ctx.createLinearGradient(cx - r, cy, cx + r, cy);
gradient.addColorStop(0, '#c62828');
gradient.addColorStop(0.5, '#e0b400');
gradient.addColorStop(1, '#2e7d32');
ctx.strokeStyle = gradient;
ctx.lineWidth = 42;
ctx.beginPath();
ctx.arc(cx, cy, r, Math.PI, 2 * Math.PI);
ctx.stroke();
Using translate() and rotate() makes the pointer code easier to read than calculating every needle coordinate manually.
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(angle);
ctx.moveTo(-12, 0);
ctx.lineTo(r - 12, 0);
ctx.stroke();
ctx.restore();
For the underlying methods, see arc(), strokeStyle, linear gradients, and the Canvas analog clock.
If a gauge communicates meaningful data, repeat the current value and maximum in nearby HTML text rather than relying on the graphic alone.
Divide the value by the maximum, multiply by the angular range, and add the starting angle.
Canvas arc and rotation APIs use radians.
Yes. Change the angular range from π radians to 2π radians.
Usually clamp or validate them before drawing.
Yes. Interpolate from the previous value to the new value with requestAnimationFrame().
Interactive dial with a range slider | Pie chart | Canvas reference
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.