Simple pie chart with HTML5

I needed to use some charts in my system, so I’ve decided to code something in HTML5 and to pass all dirty processing job to the user navigator.

After reading a little about canvas object, I got this code below:

$(document).ready( function() {
	var getColors = function( total ) {
		var r,g,b = 0;
		var colors = new Array();

		for( var i = 0; i < total; i++ ) {
			r = Math.abs(Math.floor(Math.random()*254));
			g = Math.abs(Math.floor(Math.random()*254));
			b = Math.abs(Math.floor(Math.random()*254)); 

			colors[i] = 'rgb('+r+','+g+','+b+')';
		}

		return colors;
	};

	var graph = function(obj, width, height, values, colors) {
		if( values.length == 0 && $('#'+obj).attr('id') == '' ) {
			return false;
		} else {
			var canvas = $('#'+obj)[0];

			if( !canvas.getContext ) {
				alert('Problem to load canvas, try moving your javascript code before ');
				return false;
			}
		}

		var total = 0;
		var percent = [];

		for(var i in values) {
			total += values[i];
		}

		if( typeof(colors) != 'object' && !(colors instanceof Array) ) {
			var colors = [];
			colors = getColors(values.length);
		}

		canvas.width = width;
		canvas.height = height;
		var context = canvas.getContext('2d');
		var angle_start = 0;
                var angle_end = 0;
		var point = [width/4, height/2];
		var pointradius = [width/2, height/2];
		var legend_x = pointradius[0]+((5*100)/width);
		var legend_y = pointradius[1] - height/7;
		var rect_size = (30*100)/width;
		var radius = Math.min( pointradius[0], pointradius[1] ) / 1.2;

		for(var i in values) {
			percent[i] = values[i] * 2 / total;
			angle_end += percent[i];
        	        context.beginPath();
			context.arc(point[0],point[1],radius,Math.PI*angle_start,Math.PI*angle_end,false);
			context.lineTo(point[0],point[1]);
			context.fillStyle = colors[i];
			context.fill();
			context.beginPath();
			context.rect(legend_x,legend_y,rect_size,rect_size);
			context.fillStyle = colors[i];
			context.fill();
			context.beginPath();
			context.font = '12px sans-serif';
			context.fillText(values[i].toFixed(2)+'%',(legend_x + rect_size + (15*100/width) ),(legend_y + rect_size ));
			context.fillStyle = '#000000';
			context.fill();
			angle_start += percent[i];
			legend_y += rect_size + (40*100/width);
		}
	};
)}

It has a very simple usage, just save the code above in a file named graph.js and take a look:

<!DOCTYPE>
<html>
<head>
	<script type="text/javascript" src="graph.js">&lt;/script>
	<meta http-equiv="content-type" content="charset=utf-8" />
        <meta http-equiv="X-UA-Compatible" content="chrome=1" />
</head>
<body>
	<canvas id="pieChartId">If you are reading this please download http://code.google.com/intl/pt-BR/chrome/chromeframe/</canvas>
	<script type="text/javascript">graph('pieChartId',400,200,[100,200])</script>
</body>
</html>

The example above will generate charts with random colors, but if you prefer to use your color scheme, just pass an array with the same amount of itens passed in the values array, so we have something like:

graph('pieChartId',400,200,[100,200],['#ff0000','#000000']);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s