Introduction
In my previous article “Web Painting Tool Using HTML 5 CANVAS in ASP.Net" I explained how to create a simple Web Painting tool using HTML5 and jQuery. I have used the program and using a few reference websites to draw a simple Pie Chart using HTML5 and jQuery.
There might be some question of why we need to draw our own Pie Chart since many free and third-party Pie Charts are available.
The answer to this question is that even if there are many free Pie Chart controls available, sometimes all the chart controls will not fulfill our requirements.
For example if we want to add our own watermarks to our Pie Chart, if we want to display our own alert Status Image Display, If we want to add our Company Logo to a Pie Chart and so on.
It will be hard to find the Pie Chart controls with all other extra requirement. The Customization will not be possible with other Pie Chart controls. Think if we draw and design our own Pie Chart controls and use that in our projects. There are no limitations to add all our features to draw and design our own Pie Chart. Here the limitation is up to our imagination.
For these reasons I thought to draw a Pie Chart with the following features using ASP.NET, HTML5 and jQuery.
In the Source Code Zip file you can find both Visual Studio 2010 and Visual Studio 2013 Solutions. You can use any solution depending on your Visual Studio Versions.
MY Pie Chart Features
- Pie Chart Source Data: Plot data from a database, data table, list, XML or any source depending on your requirements. The only thing you must do is to get the data from your source and bind the result to a Dropdown List. (With value and text. Here the value will be an integer for plotting the value and text to display in the label.)
- Pie Chart Number of Category: Here I have limited the Pie chart Category display from a minimum of 1 to a maximum of 12. This means here dynamically we can load the plots category depending on the data source. But we are limited since the display plots value is within 12 plots. (But the user can redesign my code easily depending on requirements.)
- Pie chart Title Text: the User can add their own Pie Chart Title and dynamically change the titles if required. Here in my example I will draw the Title TextBox text at the bottom of the Pie Chart. (The user can redesign and customize depending on your requirements if needed).
- Pie Chart Water Mark Text: In some cases we need to add our company name as Water Mark to our Pie Chart. Here in my example I will draw the Water Mark TextBox text at the center of the Pie Chart. (The user can redesign and customize depending on requirements.)
- Pie Chart Company LOGO: The User can add their own company logo to the Pie Chart. (Here for example I added my own image as a log at the top-left corner. (The user can redesign and customize depending on requirements.)
- Pie Chart Alert Image Display: You can see from the article the first image has labels, I have displayed the Pie Chart label text and alert image. If the “Alert On” radio button is checked I will display the alert image. If the “Alert Off” radio button is clicked then the alert image will not be displayed.
What is the use of the alert image?
Let's consider an actual project. For example we need to display the Pie chart for a Manufacturing factory with production result as Good and Bad. For example if the production result for each quality value is above 300 then we need to display the alert Green image and if the quality value is below 300 then we need to display the Red image with label bars.
This alert image will be easy to identify each quality result with good or bad. (Here for example I have used 2 quality checks and display Green and Red images, but users can customize depending on your requirements and add your own image and logic.)
- Save Pie Chart as Image: The user can save the Pie chart as an image.
Here we can see the Pie Chart with another theme with a Blue base but without displaying the alert image.
Code Part
Step 1
Click Start then select "All Programs" then open Visual Studio 2013 or Visual Studio 2010 depending on your installed versions, select either. In Visual Studio click "File" -> "New" -> "Project..." then seelct ASP.NET WEB Project then click Create.
Step 2
Add a new Webform and add a Canvas ELEMENT within the Section Tag.
- <SECTION style="border-style: solid; border-width: 2px; width: 1024px;">
-
- <CANVAS HEIGHT="740" WIDTH="1024px" ID="canvas">
Your browser is not supporting HTML5 Canvas. Upgrade the browser to view this program or check with Chrome or in Firefox.
Step 3
Inside the JavaScript declare the global variables and initialize the Canvas in JavaScript. In the code I have used comments to easily understand the declarations.
- Script Detail Explanations
- Script Global variable
Chart Category Color Add
Adding the Pie Chart category colors to an array. Here I have fixed it to 12 colors and 12 data to add with the Pie Chart. If you want you can add more from here. Here I have 2 sets of color combinations, one with s Green base and one with a Blue base. The user can add more depending on requirements.
- var pirChartColor = ["#6CBB3C", "#F87217", "#EAC117", "#EDDA74", "#CD7F32", "#CCFB5D", "#FDD017", "#9DC209", "#E67451", "#728C00", "#617C58", "#64E986"];
- var pirChartColor = ["#3090C7", "#BDEDFF", "#78C7C7", "#736AFF", "#7FFFD4", "#3EA99F", "#EBF4FA", "#F9B7FF", "#8BB381", "#BDEDFF", "#B048B5", "#4E387E"];
Function to add all the Plot values: This method will return the final result to be the final sum of plot values that will be used to calculate and draw the Pie Chart Angle.
- function getChartTotal(){
- var chartTotalResult = 0;
- $('#DropDownList1 option').each(function () {
-
- chartTotalResult += (typeof parseInt($(this).val()) == 'number') ? parseInt($(this).val()) : 0;
- });
-
- return chartTotalResult;
- }
Function to Draw Pie Chart: In the chart image button click I will call this JavaScript method. In this method I get a Pie Chart value and text from the Dropdown List and draw a Pie chart with those values. Inside this method I will check for all the features and add all the features to my Pie Chart. The user can customize and redesign depending on requirements.
Inside this method before each line I have added a comment that will explain each part in detail.
- function plotData() {
-
- var canvas;
- var ctx;
- var lastend = 0;
-
- var chartTotalResult = getChartTotal();
-
-
- var canWidth = 200;
- var Canheight = 150;
- var labelBarX = 100;
- var labelBarY = 100;
- var labelBarWidth = 100;
- var labelBarHeight = 100;
- var colorval = 0;
-
- var greenImage = new Image();
- var redImage = new Image();
- greenImage.src = 'images/Green.png';
- redImage.src = 'images/Red.png';
- var imagesize = 28;
-
-
- var alertCheckValue = 300;
-
- rect = {};
- rectInner = {};
-
-
- canvas = document.getElementById("canvas");
- ctx = canvas.getContext("2d");
-
- ctx.globalAlpha = 1;
-
- ctx.clearRect(0, 0, canvas.width, canvas.height);
-
-
-
-
- canWidth = (canvas.width/2)-150;
- Canheight = (canvas.height/2)-20;
-
- rect.startX = canvas.width - 280;
- rect.startY = 20;
- rect.w = canWidth / 2+80;
- rect.h = canvas.height - 60;
-
-
-
-
-
-
- var titelXVal=canWidth - 120;
- var titelYVal = canvas.height - 8;
-
- ctx.font = '32pt Calibri';
- ctx.fillStyle = "#15317E";
- ctx.fillText($('#txtTitle').val(), titelXVal, titelYVal);
-
-
- var LogoImage = new Image();
- LogoImage.src = 'images/shanu.jpg';
- var LogoImgSize = 60;
- var logoXVal = 0;
- var logolYVal = 0;
-
-
- ctx.globalAlpha = 0.6;
-
- ctx.drawImage(LogoImage, logoXVal, logolYVal, LogoImgSize, LogoImgSize);
-
- ctx.globalAlpha =1;
-
- ctx.fillStyle = "#7F462C";
- ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
-
- ctx.fillStyle = "#FFFFFF";
- rectInner.startX = rect.startX + 1;
- rectInner.startY = rect.startY + 1;
- rectInner.w = rect.w - 4;
- rectInner.h = rect.h - 4;
-
- ctx.fillRect(rectInner.startX, rectInner.startY, rectInner.w, rectInner.h);
-
-
-
- labelBarX = rect.startX+10;
- labelBarY = rect.startY+10;
- labelBarWidth = 240;
- labelBarHeight = 46;
- var labelTextXVal = labelBarX+34;
- var labelTextYXVal = labelBarY + 26;
-
- var alertImgXVal = labelBarX + 2;
- var alertImgYVal = labelBarY + 2;
-
-
-
- $('#DropDownList1 option').each(function () {
-
- ctx.fillStyle = pirChartColor[colorval];
- ctx.beginPath();
- ctx.moveTo(canWidth, Canheight);
-
- ctx.arc(canWidth, Canheight, Canheight, lastend, lastend +
- (Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult)), false);
- ctx.lineTo(canWidth, Canheight);
- ctx.fill();
- lastend += Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult);
-
- ctx.fillRect(labelBarX, labelBarY, labelBarWidth, labelBarHeight);
-
- if ($('#rdoAlaramOn:checked').val() == "rdoAlaramOn") {
-
-
-
- if (parseInt($(this).val()) >= alertCheckValue) {
- ctx.drawImage(greenImage, alertImgXVal, alertImgYVal, imagesize, imagesize);
- }
- else {
- ctx.drawImage(redImage, alertImgXVal, alertImgYVal, imagesize, imagesize);
- }
- }
-
- ctx.fillStyle = "#000000";
- ctx.font = '16pt Calibri';
- ctx.fillText($(this).text(), labelTextXVal, labelTextYXVal);
-
-
-
- labelBarY = labelBarY + labelBarHeight + 10;
- labelTextYXVal = labelBarY + labelBarHeight - 18;
- alertImgYVal = labelBarY + labelBarHeight - 40;
- colorval = colorval + 1;
-
-
-
- });
-
-
- ctx.globalAlpha = 0.1;
- ctx.font = '72pt Calibri';
- ctx.fillStyle = "#000000";
- ctx.fillText($('#txtWatermark').val(), canWidth - 120, Canheight);
- }
Function to SAVE Pie Chart
This method is called in the save image button click. In this method after confirmation the Canvas Pie chart will be saved to the local computer.
-
- function ShanuSaveImage() {
- var m = confirm("Are you sure to Save ");
- if (m) {
-
- var canvas = document.getElementById("canvas");
- document.location.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
-
- var ImageSave = document.createElement('a');
- ImageSave.download = "shanuPIEImage.png";
- ImageSave.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");;
- ImageSave.click();
- alert("Image Saved");
- }
Step 3
Bind Dropdown List Data from DataTable: In the page Load and in Button Click I will call the “
BindDropDownList()” method to populate the Pie Chart values in dataTable and bind the final result to the Dropdown List.
Here for a simple example I have used the DataTable to populate the data and bind the result to a dropdown list. You can write your own code to bind the result to the Dropdown list. You can even change the source from Dropdown List to any control depending on your requirements.
The Dropdown list items will be obtained in JavaScript and using the values the Pie chart will be created dynamically.
- protected void Page_Load(object sender, EventArgs e)
- {
- BindDropDownList();
- }
-
- protected void Button1_Click(object sender, EventArgs e)
- {
- BindDropDownList();
- }
-
- private void BindDropDownList()
- {
- DataTable dt = new DataTable();
- dt.Clear();
- dt.Rows.Clear();
- dt.Columns.Add("Names");
- dt.Columns.Add("Frequency");
- dt.Columns["Frequency"].DataType = Type.GetType("System.Int32");
-
-
- Random random = new Random();
-
- for (int i = 1; i <=Convert.ToInt32(txtChartCount.Text.Trim()); i++)
- {
- DataRow row = dt.NewRow();
- Int32 value = random.Next(100, 600);
- row["Names"] = "Pie-" + i.ToString() + " - (" + value+") ";
- row["Frequency"] = value;
- dt.Rows.Add(row);
- }
- DropDownList1.DataSource = dt;
- DropDownList1.DataTextField = "Names";
- DropDownList1.DataValueField = "Frequency";
- DropDownList1.DataBind();
-
-
- }
Complete ASPX Design Code:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
- <title>SHANU - >PIE Chart USIN HTML 5 CANVAS</title>
- <meta http-equiv="Page-Enter" content="blendTrans(Duration=0.0)" />
- <meta http-equiv="Page-Exit" content="blendTrans(Duration=0.0)" />
- <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/>
-
- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
-
- <SCRIPT>
-
-
-
- var pirChartColor = ["#6CBB3C", "#F87217", "#EAC117", "#EDDA74", "#CD7F32", "#CCFB5D", "#FDD017", "#9DC209", "#E67451", "#728C00", "#617C58", "#64E986"];
-
-
- function getChartTotal(){
- var chartTotalResult = 0;
- $('#DropDownList1 option').each(function () {
-
- chartTotalResult += (typeof parseInt($(this).val()) == 'number') ? parseInt($(this).val()) : 0;
- });
-
- return chartTotalResult;
- }
-
- function plotData() {
-
- var canvas;
- var ctx;
- var lastend = 0;
-
- var chartTotalResult = getChartTotal();
-
-
- var canWidth = 200;
- var Canheight = 150;
- var labelBarX = 100;
- var labelBarY = 100;
- var labelBarWidth = 100;
- var labelBarHeight = 100;
- var colorval = 0;
-
- var greenImage = new Image();
- var redImage = new Image();
- greenImage.src = 'images/Green.png';
- redImage.src = 'images/Red.png';
- var imagesize = 28;
-
-
- var alertCheckValue = 300;
-
- rect = {};
- rectInner = {};
-
-
- canvas = document.getElementById("canvas");
- ctx = canvas.getContext("2d");
-
- ctx.globalAlpha = 1;
-
- ctx.clearRect(0, 0, canvas.width, canvas.height);
-
-
-
-
- canWidth = (canvas.width/2)-150;
- Canheight = (canvas.height/2)-20;
-
- rect.startX = canvas.width - 280;
- rect.startY = 20;
- rect.w = canWidth / 2+80;
- rect.h = canvas.height - 60;
-
-
-
-
-
-
- var titelXVal=canWidth - 120;
- var titelYVal = canvas.height - 8;
-
- ctx.font = '32pt Calibri';
- ctx.fillStyle = "#15317E";
- ctx.fillText($('#txtTitle').val(), titelXVal, titelYVal);
-
-
- var LogoImage = new Image();
- LogoImage.src = 'images/shanu.jpg';
- var LogoImgSize = 60;
- var logoXVal = 0;
- var logolYVal = 0;
-
-
- ctx.globalAlpha = 0.6;
-
- ctx.drawImage(LogoImage, logoXVal, logolYVal, LogoImgSize, LogoImgSize);
-
- ctx.globalAlpha =1;
-
- ctx.fillStyle = "#7F462C";
- ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
-
- ctx.fillStyle = "#FFFFFF";
- rectInner.startX = rect.startX + 1;
- rectInner.startY = rect.startY + 1;
- rectInner.w = rect.w - 4;
- rectInner.h = rect.h - 4;
-
- ctx.fillRect(rectInner.startX, rectInner.startY, rectInner.w, rectInner.h);
-
-
-
- labelBarX = rect.startX+10;
- labelBarY = rect.startY+10;
- labelBarWidth = 240;
- labelBarHeight = 46;
- var labelTextXVal = labelBarX+34;
- var labelTextYXVal = labelBarY + 26;
-
- var alertImgXVal = labelBarX + 2;
- var alertImgYVal = labelBarY + 2;
-
-
-
- $('#DropDownList1 option').each(function () {
-
- ctx.fillStyle = pirChartColor[colorval];
- ctx.beginPath();
- ctx.moveTo(canWidth, Canheight);
-
- ctx.arc(canWidth, Canheight, Canheight, lastend, lastend +
- (Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult)), false);
- ctx.lineTo(canWidth, Canheight);
- ctx.fill();
- lastend += Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult);
-
- ctx.fillRect(labelBarX, labelBarY, labelBarWidth, labelBarHeight);
-
- if ($('#rdoAlaramOn:checked').val() == "rdoAlaramOn") {
-
-
-
- if (parseInt($(this).val()) >= alertCheckValue) {
- ctx.drawImage(greenImage, alertImgXVal, alertImgYVal, imagesize, imagesize);
- }
- else {
- ctx.drawImage(redImage, alertImgXVal, alertImgYVal, imagesize, imagesize);
- }
- }
-
- ctx.fillStyle = "#000000";
- ctx.font = '16pt Calibri';
- ctx.fillText($(this).text(), labelTextXVal, labelTextYXVal);
-
-
-
- labelBarY = labelBarY + labelBarHeight + 10;
- labelTextYXVal = labelBarY + labelBarHeight - 18;
- alertImgYVal = labelBarY + labelBarHeight - 40;
- colorval = colorval + 1;
-
-
-
- });
-
-
- ctx.globalAlpha = 0.1;
- ctx.font = '72pt Calibri';
- ctx.fillStyle = "#000000";
- ctx.fillText($('#txtWatermark').val(), canWidth - 120, Canheight);
- }
-
-
- function ShanuSaveImage() {
- var m = confirm("Are you sure to Save ");
- if (m) {
-
-
- var canvas = document.getElementById("canvas");
- document.location.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
-
- var ImageSave = document.createElement('a');
- ImageSave.download = "shanuPIEImage.png";
- ImageSave.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");;
- ImageSave.click();
- alert("Image Saved");
- }
- }
-
-
- plotData();
- </script>
- </head>
- <body>
- <form id="form1" runat="server">
- <img src="images/blank.gif" alt="" width="1" height="10" />
- <table width="99%" style=" border-bottom:3px solid #3273d5;">
- <tr>
-
- <td width=" 250">
- <table width="99%">
- <tr>
- <td>
- Created by SHANU
-
- </td>
-
-
- </tr>
- </table>
- </td>
- <td class="style1" align="center">
- <h3>ASP.NET PIE Chart USING HTML5 and Jquery</h3>
-
-
- </td>
-
- </tr>
- </table>
- <img src="~/Images/blank.gif" alt="" width="1" height="10" />
- <table style=" padding: 5px;width: 99%;table-layout:fixed; border-bottom:3px solid #3273d5;"">
- <tr>
- <td >
- <table width="100%" >
- <tr>
-
- <td style="background-color:#ECF3F4;"" >
- Enter Pie Chart Draw Count:
-
- </td>
- <td width="90">
-
-
- <asp:TextBox ID="txtChartCount" runat="server" Height="26px" MaxLength="2" Width="90"
- onkeypress="if(event.keyCode<48 || event.keyCode>57)event.returnValue=false;" >7</asp:TextBox><br />
- <asp:RangeValidator ID="RangeValidator1" Type="Integer" MinimumValue="1" MaximumValue="12" ControlToValidate="txtChartCount" runat="server" ErrorMessage="No <= 12"></asp:RangeValidator>
- </td>
- <td style="background-color:#ECF3F4;"" >
- Click Button to fill PIE Chart Data:
-
- </td>
- <td>
- <asp:DropDownList ID="DropDownList1" runat="server" Width="140px" Height="36px">
- </asp:DropDownList>
- </td>
- <td>
- <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Populate List" BackColor="#336699" BorderColor="White" BorderStyle="Solid" BorderWidth="1px" Font-Bold="True" ForeColor="#CCFFFF" Height="37px" />
- </td>
- <td style="background-color:#ECF3F4;" >
- Click to Draw Dynamic Pic Chart:
-
- </td>
- <td rowspan="2">
-
-
- <img src="images/piechart.png" onClick="plotData()" alt="Click to Draw PIE Chart" />
- </td>
- <td style="background-color:#ECF3F4;"" rowspan="2">
- Save Pic Chart:
-
- </td>
- <td rowspan="2">
- <img src="images/Save.png" onClick="ShanuSaveImage()" alt="Click to Save PIE Chart" />
- </td>
-
- </tr>
-
-
- <tr>
-
- <td style="background-color:#ECF3F4;"" >
- Enter Chart Title:
-
- </td>
- <td >
-
-
- <asp:TextBox ID="txtTitle" runat="server" Height="26px" MaxLength="40" Width="120" >SHANU PIE Chart</asp:TextBox><br />
- </td>
- <td style="background-color:#ECF3F4;"" >
- Chart WaterMark:
-
- </td>
- <td >
-
-
- <asp:TextBox ID="txtWatermark" runat="server" Height="26px" MaxLength="40" Width="120px" >SHANU</asp:TextBox><br />
- </td>
- <td style="background-color:#ECF3F4;"" >
- Alert Status </td>
- <td >
-
-
- <asp:RadioButton ID="rdoAlaramOn" runat="server" Checked="True" GroupName="Alaram" Text="Alert On" />
- <asp:RadioButton ID="rdoAlaramOff" runat="server" GroupName="Alaram" Text="Alert Off" />
-
-
- <br />
- </td>
- </tr>
- </table>
- </td>
- </tr>
- </table>
- <img src="~/Images/blank.gif" alt="" width="1" height="10" />
- <table width="99%" class="search">
- <table style=" solid 2px #3273d5; padding: 5px;width: 99%;table-layout:fixed; border-top:3px solid #3273d5;"">
- <tr>
- <td align="center">
- <SECTION style="border-style: solid; border-width: 2px; width: 1024px;">
-
- <CANVAS HEIGHT="740" WIDTH="1024px" ID="canvas">
- Your browser is not supporting HTML5 Canvas .Upgrade Browser to view this program or check with Chrome or in Firefox.
- </CANVAS>
-
- </SECTION>
- </td>
- </tr>
- </table>
- </form>
-
- </body>
- </html>
- Points of Interest
Working with HTML5 is really fun. I hope you enjoyed reading my article. I will be happy if someone benefits from my article.
Tested browsers: - Chrome
- Firefox
- IE10