Simple Pie Graphs Using <canvas> element in HTML 5
Now a days graphs are playing a major role to visualise the statistics in the web applications. With the help of these graphs, user can see all the information in detail at a glance. One popular kind among those graphs is Pie Graphs. So i continued my work for plotting Pie diagram with the help of simple Javascript & HTML5 <canvas> element. The canvas element properties such as 'arc()', 'beginPath()', 'lineTo()' & 'fill()' are used in this example. Let us go through each step for better understanding.
Define the canvas element in your document body as shown below. You can apply styles either by using "style" tag (inline CSS) or defined class in separate .css file.
Define your values in the form of an array as shown below. To display different filled colors for each section, Let us define each color for each value we defined earlier in another array as shown below.
Define the canvas element in your document body as shown below. You can apply styles either by using "style" tag (inline CSS) or defined class in separate .css file.
<canvas id="canvas" width="800" height="500"></canvas>
Define your values in the form of an array as shown below. To display different filled colors for each section, Let us define each color for each value we defined earlier in another array as shown below.
<script language="javascript" type="text/javascript"> var myColor = ["#ECD078","#D95B43","#C02942","#542437","#53777A"]; var myData = [10,30,50,25,40]; </script>I defined a function called 'plotData()' to display the Pie Diagram in the document. You can see the function definition and calling method in the below section.
<script language="javascript" type="text/javascript">
function plotData() {
var canvas;
var ctx;
var lastend = 0;
var myTotal = 0;
for (var j = 0; j < myData.length; j++) {
myTotal += (typeof myData[j] == 'number') ? myData[j] : 0;
}
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < myData.length; i++) {
ctx.fillStyle = myColor[i];
ctx.beginPath();
ctx.moveTo(200,150);
ctx.arc(200,150,150,lastend,lastend+(Math.PI*2*(myData[i]/myTotal)),false);
ctx.lineTo(200,150);
ctx.fill();
lastend += Math.PI*2*(myData[i]/myTotal);
}
}
plotData();
</script>
Whereever you call this function using 'plotData();', it creates a Pie Diagram in the defined canvas of your document body.
y u stopped posting in blogs..
ReplyDelete