Skip to content

Instantly share code, notes, and snippets.

@joncombe
Created January 27, 2012 04:55
Show Gist options
  • Save joncombe/1687068 to your computer and use it in GitHub Desktop.
Save joncombe/1687068 to your computer and use it in GitHub Desktop.
Experiments with ExCanvas: Pie Charts (See http://joncom.be/code/excanvas-piechart/)
function PieChart(iMiddleX, iMiddleY, iRadius,
iExplodeDistance, bShowShadow, iDonutRadius, aData) {
// draw shadow
if (bShowShadow == true) {
var iStartAngle = 0;
var iShadowOffset = (iRadius / 45);
for (var i = 0; i < aData.length; i++) {
iStartAngle = DrawSlice(oColors.shadow,
iMiddleX + iShadowOffset,
iMiddleY + iShadowOffset,
(iRadius * 1), iExplodeDistance,
iStartAngle, aData[i]);
}
}
// draw slices
var iStartAngle = 0;
for (var i = 0; i < aData.length; i++) {
iStartAngle = DrawSlice(oColors.colors[i],
iMiddleX, iMiddleY, iRadius,
iExplodeDistance, iStartAngle, aData[i]);
}
// draw donut
if (iDonutRadius > 0) {
// 4 half circles? IE hackery :(
oCTX.globalCompositeOperation = "destination-out";
iStartAngle = DrawSlice(oColors.shadow,
iMiddleX, iMiddleY,
iDonutRadius, 0, 0, 50);
iStartAngle = DrawSlice(oColors.shadow,
iMiddleX, iMiddleY,
iDonutRadius, 0, iStartAngle, 50);
iStartAngle = DrawSlice(oColors.shadow,
iMiddleX, iMiddleY,
iDonutRadius, 0, (iStartAngle + 5), 50);
iStartAngle = DrawSlice(oColors.shadow,
iMiddleX, iMiddleY,
iDonutRadius, 0, (iStartAngle + 5), 50);
}
// slice drawing
function DrawSlice(sColor, iMiddleX, iMiddleY, iRadius,
iExplodeDistance, iStartAngle, iPercentage) {
// calculate angles
var iEndAngle = ((iPercentage * 3.6) + iStartAngle);
var iRadiansFrom = DegreesToRadians(iStartAngle);
var iRadiansTo = DegreesToRadians(iEndAngle);
var iRadiansMid = (((iRadiansTo - iRadiansFrom) / 2) + iRadiansFrom);
// calculate explode
var iExplodeModify = (iExplodeDistance * (1 - (iPercentage / 100)));
iMiddleX += (Math.cos(iRadiansMid) * iExplodeModify);
iMiddleY += (Math.sin(iRadiansMid) * iExplodeModify);
// draw
oCTX.fillStyle = sColor;
oCTX.beginPath();
oCTX.moveTo(iMiddleX, iMiddleY);
oCTX.arc(iMiddleX, iMiddleY, iRadius, iRadiansFrom, iRadiansTo, false);
oCTX.fill();
// return end point angle
return iEndAngle;
}
}
function DegreesToRadians(iDegrees) {
return (Math.PI / 180) * (iDegrees - 90);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment