Pie & donut chart with Raphael.js
by Frank Topel
HTML
<script src="http://github.com/DmitryBaranovskiy/raphael/raw/master/raphael-min.js"></script>
<script src="https://g.raphaeljs.com/g.raphael.js"></script>
<script src="https://g.raphaeljs.com/g.pie.js"></script>
<table style="display: none;">
<tbody>
<tr>
<th scope="row">Ruby</th>
<td>40%</td>
</tr>
<tr>
<th scope="row">JavaScript</th>
<td>26%</td>
</tr>
<tr>
<th scope="row">Shell</th>
<td>5%</td>
</tr>
<tr>
<th scope="row">Python</th>
<td>5%</td>
</tr>
<tr>
<th scope="row">PHP</th>
<td>4%</td>
</tr>
<tr>
<th scope="row">C</th>
<td>4%</td>
</tr>
<tr>
<th scope="row">Perl</th>
<td>3%</td>
</tr>
<tr>
<th scope="row">C++</th>
<td>2%</td>
</tr>
<tr>
<th scope="row">Java</th>
<td>2%</td>
</tr>
<tr>
<th scope="row">Objective-C</th>
<td>2%</td>
</tr>
</tbody>
</table>
<div id="holder"></div>
<div class="chart donut"></div>
<div class="chart pie"></div>
SCSS
.chart {
background-image: linear-gradient(0deg, #eee, #fff);
box-shadow: 0 0 5px #333;
display: inline-block;
position: relative;
height: 400px;
width: 400px;
&:after {
content: "Chart";
display: block;
position: absolute;
bottom: -20px;
left: 0;
font-family: "univers 75", Arial, Helvetica, sans-serif;
text-transform: uppercase;
}
}
#holder {
margin: -350px 0 0 -350px;
width: 700px;
height: 700px;
}
JavaScript
Raphael.fn.pieChart = function (cx, cy, r, values, labels, stroke) {
var paper = this,
rad = Math.PI / 180,
chart = this.set();
function sector(cx, cy, r, startAngle, endAngle, params) {
var x1 = cx + r * Math.cos(-startAngle * rad),
x2 = cx + r * Math.cos(-endAngle * rad),
y1 = cy + r * Math.sin(-startAngle * rad),
y2 = cy + r * Math.sin(-endAngle * rad);
return paper.path(["M", cx, cy, "L", x1, y1, "A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2, "z"]).attr(params);
}
var angle = 0,
total = 0,
start = 0,
process = function (j) {
var value = values[j],
angleplus = 360 * value / total,
popangle = angle + (angleplus / 2),
color = Raphael.hsb(start, .75, 1),
ms = 500,
delta = 30,
bcolor = Raphael.hsb(start, 1, 1),
p = sector(cx, cy, r, angle, angle + angleplus, {fill: "90-" + bcolor + "-" + color, stroke: stroke, "stroke-width": 3}),
txt = paper.text(cx + (r + delta + 55) * Math.cos(-popangle * rad), cy + (r + delta + 25) * Math.sin(-popangle * rad), labels[j]).attr({fill: bcolor, stroke: "none", opacity: 0, "font-size": 20});
p.mouseover(function () {
p.stop().animate({transform: "s1.1 1.1 " + cx + " " + cy}, ms, "elastic");
txt.stop().animate({opacity: 1}, ms, "elastic");
}).mouseout(function () {
p.stop().animate({transform: ""}, ms, "elastic");
txt.stop().animate({opacity: 0}, ms);
});
angle += angleplus;
chart.push(p);
chart.push(txt);
start += .1;
};
for (var i = 0, ii = values.length; i < ii; i++) {
total += values[i];
}
for (i = 0; i < ii; i++) {
process(i);
}
return chart;
};
$(function () {
var values = [],
...