Skip to content

Instantly share code, notes, and snippets.

@sketchytech
Created August 23, 2016 11:36
Show Gist options
  • Save sketchytech/ce377356b22ba0c0801d37fcc7f10da6 to your computer and use it in GitHub Desktop.
Save sketchytech/ce377356b22ba0c0801d37fcc7f10da6 to your computer and use it in GitHub Desktop.
Percentage Circle in HTML Canvas
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="250"></canvas>
<script>
function degreesToRadians(deg) {
return (deg/180) * Math.PI;
}
function percentToRadians(percentage) {
// convert the percentage into degrees
var degrees = percentage * 360 / 100;
// and so that arc begins at top of circle (not 90 degrees) we add 270 degrees
return degreesToRadians(degrees + 270);
}
function drawPercentageCircle(percentage, radius, canvas) {
var context = canvas.getContext('2d');
canvas.style.backgroundColor = 'black';
var x = canvas.width / 2;
var y = canvas.height / 2;
var startAngle = percentToRadians(0);
var endAngle = percentToRadians(percentage);
// set to true so that we draw the missing percentage
var counterClockwise = true;
context.beginPath();
context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
context.lineWidth = 15;
// line color
context.strokeStyle = 'lightyellow';
context.stroke();
// set to false so that we draw the actual percentage
counterClockwise = false;
context.beginPath();
context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
context.lineWidth = 15;
// line color
context.strokeStyle = 'lightblue';
context.stroke();
// now draw the inner text
context.font = radius/2.5 + "px Helvetica";
context.fillStyle = "lightblue";
context.textAlign = "center";
// baseline correction for text
context.fillText(percentage+"%", x, y*1.05);
}
// implantation happens here
var canvas = document.getElementById('myCanvas');
var percentage = 70;
var radius;
if (myCanvas.height < myCanvas.width) {
radius = myCanvas.height / 3;
}
else {
radius = myCanvas.width / 3;
}
drawPercentageCircle(percentage, radius, canvas);
</script>
</body>
</html>
@sketchytech
Copy link
Author

Here's the result of the above code:

percentagecircle

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment