Pie Chart
HTML5 CSS3 Pie Chart with fall-back to data-table
HTML
<canvas id="canvas" width="300" height="300"></canvas>
<table id="mydata">
<tr>
<th>Lang</th>
<th>Value</th>
</tr>
<tr>
<td><a href="javascript:activeSegment=(activeSegment==0?99:0);redrawGraph();">JavaScript</a></td>
<td>100</td>
</tr>
<tr>
<td><a href="javascript:activeSegment=(activeSegment==1?99:1);redrawGraph();">CSS</a></td>
<td>200</td>
</tr>
<tr>
<td><a href="javascript:activeSegment=(activeSegment==2?99:2);redrawGraph();">HTML</a></td>
<td>300</td>
</tr>
<tr>
<td><a href="javascript:activeSegment=(activeSegment==3?99:3);redrawGraph();">PHP</a></td>
<td>50</td>
</tr>
<tr>
<td><a href="javascript:activeSegment=(activeSegment==4?99:4);redrawGraph();">MySQL</a></td>
<td>30</td>
</tr>
<tr>
<td><a href="javascript:activeSegment=(activeSegment==5?99:5);redrawGraph();">Apache</a></td>
<td>10</td>
</tr>
<tr>
<td><a href="javascript:activeSegment=(activeSegment==6?99:6);redrawGraph();">Linux</a></td>
<td>30</td>
</tr>
</table>
CSS
* {
font-family: Arial;
}
table {
margin-left: 10px;
/* border-collapse: collapse; */
}
td {
padding: 5px;
border: 1px solid black;
}
canvas {
float: left;
}
JavaScript
window.activeSegment = 99;
window.redrawGraph = function () { //keep the global space clean
///// STEP 0 - setup
// source data table and canvas tag
var data_table = document.getElementById('mydata');
var canvas = document.getElementById('canvas');
var td_index = 1; // which TD contains the data
///// STEP 1 - Get the, get the, get the data!
// get the data[] from the table
var tds, data = [],
color, colors = [],
value = 0,
total = 0;
var trs = data_table.getElementsByTagName('tr'); // all TRs
var tableHeaderHeight = parseInt(getComputedStyle(trs[0])['height'].replace('px'), 10);
canvas.style.height = (parseInt(getComputedStyle(data_table)['height'].replace('px'), 10) - tableHeaderHeight) + 'px';
canvas.style.marginTop = (tableHeaderHeight + 2) + 'px';
for (var i = 0; i < trs.length; i++) {
tds = trs[i].getElementsByTagName('td'); // all TDs
if (tds.length === 0) continue; // no TDs here, move on
// get the value, update total
value = parseFloat(tds[td_index].innerHTML);
data[data.length] = value;
total += value;
// random color
color = getColor(i);
trs[i].style.backgroundColor = color; // color this TR
}
///// STEP 2 - Draw pie on canvas
// exit if canvas is not supported
if (typeof canvas.getContext === 'undefined') {
return;
}
// get canvas context, determine radius and center
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
var canvas_size = [canvas.width, canvas.height];
var radius = (Math.min(canvas_size[0], canvas_size[1]) / 2) * .95;
var center = [canvas_size[0] / 2, canvas_size[1] / 2];
var sofar = 0; // keep track of progress
// loop the...