diff --git a/PieChart/piechart.html b/PieChart/piechart.html index 76d6aaa..40bc37e 100644 --- a/PieChart/piechart.html +++ b/PieChart/piechart.html @@ -3,36 +3,94 @@ Pie Chart + - - - + + + + + + - + \ No newline at end of file diff --git a/PieChart/piechart.js b/PieChart/piechart.js index 5969bb2..f94b69e 100644 --- a/PieChart/piechart.js +++ b/PieChart/piechart.js @@ -25,6 +25,16 @@ function PieChart(id, o) { this.includeLabels = o.includeLabels; } this.data = o.data ? o.data : [30, 70, 45, 65, 20, 130]; // in degrees + + var dataLength = this.data.length, + totalCount = 0; + for(i = 0; i < dataLength; i++) + { + totalCount += this.data[i] + } + this.multiplier = 360/totalCount; + + this.labels = o.labels ? o.labels : ["First", "Second", "Third", "Fourth", "Fifth", "Sixth"]; this.colors = o.colors ? o.colors : [ ["#bbddb3", "#1d8e04"], // green @@ -36,6 +46,7 @@ function PieChart(id, o) { ]; this.canvas = document.getElementById(id); + } PieChart.prototype = { @@ -49,20 +60,24 @@ PieChart.prototype = { draw: function() { var self = this; var context = this.canvas.getContext("2d"); + if(window.devicePixelRatio == 2) {context.scale(1,1);} for (var i = 0; i < this.data.length; i++) { this.drawSegment(this.canvas, context, i, this.data[i], false, this.includeLabels); } }, drawSegment: function(canvas, context, i, size, isSelected, includeLabels) { + size *= this.multiplier; var self = this; context.save(); var centerX = Math.floor(canvas.width / 2); var centerY = Math.floor(canvas.height / 2); radius = Math.floor(canvas.width / 2); - + var startingAngle = self.degreesToRadians(self.sumTo(self.data, i)); + startingAngle *= this.multiplier; var arcSize = self.degreesToRadians(size); + var endingAngle = startingAngle + arcSize; context.beginPath(); @@ -73,7 +88,7 @@ PieChart.prototype = { isSelected ? context.fillStyle = self.colors[i][1] : context.fillStyle = self.colors[i][0]; - + context.fill(); context.restore(); @@ -87,16 +102,16 @@ PieChart.prototype = { context.save(); var x = Math.floor(canvas.width / 2); var y = Math.floor(canvas.height / 2); - var angle = self.degreesToRadians(self.sumTo(self.data, i)); - + var angle = self.degreesToRadians(self.sumTo(self.data, i)*this.multiplier); + context.translate(x, y); context.rotate(angle); context.textAlign = "right"; - var fontSize = Math.floor(canvas.height / 25); + var fontSize = Math.floor(canvas.height / 30); context.font = fontSize + "pt Helvetica"; var dx = Math.floor(canvas.width * 0.5) - 10; - var dy = Math.floor(canvas.height * 0.05); + var dy = Math.floor(canvas.height * 0.04); context.fillText(self.labels[i], dx, dy); context.restore(); @@ -106,7 +121,7 @@ PieChart.prototype = { var self = this; var context = this.canvas.getContext("2d"); var size = self.data[i]; - + size *= this.multiplier; self.drawSegmentLabel(this.canvas, context, i, size, false); }, @@ -125,4 +140,3 @@ PieChart.prototype = { } -