Pure JavaScript pie chart generator
by gabrieleromanato
HTML
<h1>Pie Chart Generator</h1>
CSS
div.chart {
position: relative;
border: 1px solid #d3d3d3;
margin: 2em auto;
}
div.chart span {
display: block;
width: 2px;
height: 2px;
background: #000000;
position: absolute;
}
ul {
list-style: square;
width: 8em;
margin: 1em auto;
}
h1 {
text-align: center;
}
JavaScript
var misc = {
math: {
justNumber: function(stringToClean) {
return parseFloat(stringToClean.toString().replace(/[^0-9\.\-]/g, ''));
},
degToRad: function(angleInDegrees) {
return angleInDegrees * Math.PI / 180;
}
},
js: {
getRandomColor: function() {
return 'rgb(' + Math.round(Math.random() * 254) + ', ' + Math.round(Math.random() * 254) + ', ' + Math.round(Math.random() * 254) + ')';
}
}
}
var pieChart = function(pieName, radius, pieData) {
var pieDiv = document.createElement('div'),
radiusSquared = Math.pow(radius, 2);
pieDiv.id = pieName;
pieDiv.className = 'chart';
pieDiv.style.width = radius * 2 + 'px';
pieDiv.style.height = radius * 2 + 'px';
document.body.appendChild(pieDiv);
this.renderPoint = function(x, y, pointColor) {
var newPoint = document.createElement('span');
newPoint.style.left = x + radius + 'px';
newPoint.style.top = y + radius + 'px';
newPoint.style.backgroundColor = pointColor;
pieDiv.appendChild(newPoint);
return {
x: x + radius,
y: y + radius
};
};
this.renderCircle = function() {
var x = -radius;
while (x < radius) {
x++;
y = Math.sqrt(radiusSquared - Math.pow(x, 2));
this.renderPoint(x, y); // for the bottom semicircle
this.renderPoint(x, pieDiv.offsetHeight - y - radius * 2); // for the top semicircle
}
};
this.rotatePoint = function(origPoint, cosTheta, sinTheta) {
return {
x: origPoint.x * cosTheta - origPoint.y * sinTheta,
y: origPoint.x * sinTheta + origPoint.y * cosTheta
};
};
this.renderLine = function(startPoint, endPoint, rotateBy, lineColor) { // render a straight line (y=mx+c)
var rotateByInRadians = misc.math.degToRad(rotateBy),
cosTheta, sinTheta;
...