I recently built a JavaScript game for which I needed a way to visually show the player’s health. The game already had a HUD where the health information was displayed. But I wanted a better way to inform about the amount of health left and I chose to implement this like a meter widget.

Below is the final result (also you can see it in live in the game):

This post explains how to convert the player health, which is in percentage to a circle to draw in HTML5 canvas.

##Drawing circles in Canvas:

Canvas offers a method `arc()` to draw circles. This method’s signature is:

In that, `startAngle` and `endAngle` is what we are interested in. By converting the health percentage to start and end angles, we can draw a arc that correlates with the percentage.

Function to convert degrees to radians:

`startAngle` and `endAngle` accepts their values in radians. But I persoanlly feel one can easily understand degrees instead of radians. So, we need a function that converts degrees to radians.

Function to convert percentage to radians:

Now that we have our degree-to-radian converter in place, we can move to next step of converting percentage to radians.

In the context of Canvas arc API, 0 degrees starts at circle’s east end, 90 degrees is south, 180 degrees is west and 270 degrees is north. Since I wanted my arc/circle to begin at top/north, I am adding that to percentage calculation. If you want your arc to start at different end points, you can add respective degrees to the above formula.

Combining all - drawing percenate as circle in canvas

Here’s the Fiddle where you can play around with the code and see the results for yourself and here’s the JavaScript game where this has been implemented.