Skip to content

Instantly share code, notes, and snippets.

@DanBrink91
Created February 22, 2014 21:07
Show Gist options
  • Save DanBrink91/9162450 to your computer and use it in GitHub Desktop.
Save DanBrink91/9162450 to your computer and use it in GitHub Desktop.
Basic Pie Graph rendering in canvas
var canvas = document.getElementById("theCanvas");
var ctx = canvas.getContext("2d");
var middle = {x: canvas.width / 2, y: canvas.height / 2};
var PI2 = Math.PI * 2;
var radius = 100;
var slices = [25, 50, 25, 100];
var total = slices.reduce(function(a, b) { return a+b; });
var colors = ["red", "blue", "green", "yellow", "orange", "purple", "teal"];
ctx.lineWidth = 5;
ctx.strokeStyle = "#000";
ctx.fillStyle = "red";
// Draw initial circle
ctx.beginPath();
ctx.arc(middle.x, middle.y, radius, 0, PI2, false);
ctx.closePath();
ctx.stroke();
// Draw slices
var start_angle = 0;
for(var i = slices.length; i--;)
{
var ratio = slices[i] / total;
var delta_angle = PI2 * ratio;
var end_angle = start_angle + delta_angle;
ctx.fillStyle = colors[i% colors.length];
ctx.beginPath();
ctx.moveTo(middle.x, middle.y);
ctx.arc(middle.x, middle.y, radius, start_angle, end_angle);
ctx.lineTo(middle.x, middle.y);
ctx.closePath();
ctx.fill();
ctx.stroke();
start_angle = end_angle;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment