Skip to content

Instantly share code, notes, and snippets.

@SamChristy
Last active December 12, 2015 07:09
Show Gist options
  • Select an option

  • Save SamChristy/4734446 to your computer and use it in GitHub Desktop.

Select an option

Save SamChristy/4734446 to your computer and use it in GitHub Desktop.
Simple function for creating pretty canvas pie charts.
/**
* @author Sam Christy <sam_christy@hotmail.co.uk>
* @licence GNU GPL
*/
var cs1 = {
r : Math.floor(Math.random() * 256),
g : Math.floor(Math.random() * 256),
b : Math.floor(Math.random() * 256)
};
var cs2 = {
r : Math.floor(Math.random() * 256),
g : Math.floor(Math.random() * 256),
b : Math.floor(Math.random() * 256)
};
cs1 = {
r : 90,
g : 69,
b : 114
};
cs2 = {
r : 207,
g : 201,
b : 217
};
function pieChart(c, data, cx, cy, r, lx, ly){
c.save();
c.shadowOffsetX = 2;
c.shadowOffsetY = 2;
c.shadowBlur = 8;
c.shadowColor = "#777";
c.arc(cx, cy, r, 0, Math.PI * 2, false);
c.fill();
c.restore();
var total = 0;
for(var i = 0; i < data.length; i++)
total += data[i][1];
// Start at 12 o'clock.
var sliceStart = Math.PI / -2;
// For each slice...
for(var i = 0; i < data.length; i++){
var delta = data[i][1] / total * Math.PI * 2;
var sliceEnd = sliceStart + delta;
// Calculate and set the colours.
var sliceColour = interp((i + 1) / data.length, cs1, cs2);
c.fillStyle = "rgb(" + sliceColour.r + "," + sliceColour.g + "," + sliceColour.b + ")";
// Draw the value's slice.
c.beginPath();
c.moveTo(cx, cy);
c.arc(cx, cy, r, sliceStart, sliceEnd, false);
c.closePath();
c.stroke();
c.fill();
// Draw the slice's key on the legend.
c.fillRect(lx, ly + 34 * i, 20, 20);
c.fillStyle = "#000";
c.fillText(data[i][0], lx + 28, ly + 16 + 34 * i );
sliceStart = sliceEnd;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment