MVC Dynamic Donut Chart Using Web API, AngularJS And JQuery

donut

Introduction:

In our previous article we saw in detail about how to draw Bar, Line, Pie and Bar & Line Chart in MVC web applications. In this article we will see how to draw Donut Chart for MVC application using HTML5 Canvas, JQuery, Web API and AngularJS.

In this series we will see one-by-one in detail starting from:

  1. MVC Dynamic Bar Chart using WEB API, AngularJS and JQuery
  2. MVC Dynamic Line Chart using WEB API, AngularJS and JQuery
  3. MVC Dynamic Pie Chart using WEB API, AngularJS and JQuery
  4. MVC Dynamic Line & Bar Chart using WEB API, AngularJS and JQuery
  5. MVC Dynamic Donut Chart using WEB API, AngularJS and JQuery
  6. MVC Dynamic Bubble Chart using WEB API, AngularJS and JQuery

Our Chart Features

Features

  1. Chart Source Data:

    Using WEB API and AngularJS we will be loading chart data from database to a Combobox. In our JQuery we will be plotting chart details from the Combobox.

  2. Chart Number of Category:

    Chart Items will be dynamically loaded from database. Here we will plot all the Items in Combobox. It’s good to plot less than 12 Items per chart.

  3. Chart Title Text:

    User can add their own Chart Title and dynamically change the titles if required. Here in our example we will draw the Title Textbox text at the Bottom of the Chart. (User can redesign and customize as per your requirements if needed).

  4. Chart Water Mark Text:

    In some cases we need to add our Company name as Water Mark to our Chart. Here in our example we will draw the Water mark Textbox text at the center of the Chart. (User can redesign and customize as per your requirements if needed).

  5. Chart Company LOGO:

    User can add their own Company logo to the Chart.(Here for sample we have added my own image as a Logo at the Top left corner.( User can redesign and customize as per your requirements if needed.).

  6. Chart Alert Image Display:

    If the “Alert On” radio button is checked we will display the Alert Image. If the “Alert Off” radio button is clicked then the Alert Image will not be displayed. In JQuery we have declared alertCheckValue = 90; and we check the plot data with this aleartcheckValue and if the plot value is greater than this check value then we will display the alert image in the legend.

    What is the use of Alert Image?

    Let’s consider a real time project. For example we need to display the chart for a Manufacturing factory with production result as Good and Bad. For example if production result for each quality value is above 90 we need to display the Alert green Image and if the quality value is below 90 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 a sample we have used for quality check and display green and red image, but users can customize as per your requirement and add your own image and logics.).

  7. Save Chart as Image: user can save the chart as Image.

  8. Chart Theme :

    Here we have created 2 themes, Blue and Green, for our Chart. We can see both theme outputs here. User can also add any number of themes as they are required.

    Blue Theme

    Blue Theme

    Green Theme

    Green Theme

In this Article we have 2 parts

  1. Chart Item and Value Insert/Update to database, Select Chart Item and Value to Combobox from database using WEB API, AngularJS.

  2. Using JQuery Draw our own Chart to HTML5 Canvas tag in our MVC page.

Prerequisites

Visual Studio 2015: You can download it from here.

Code Part

In Code part we can see 3 Steps,

Step 1: Explains about how to create a sample Database, Table, Stored procedure to select, Insert and Update Chart data to SQL Server.

Step 2: Explains about how to create a WEB API to get the data and bind the result to MVC page using AngularJS.

Step 3: Explains about how to draw our own Chart to our MVC Web application using JQuery.

Step 1: Script to create Table and Stored Procedure

We will create aItemMaster table under the Database ‘ItemsDB. The following is the script to create a database, table and sample insert query. Run this script in your SQL Server. I have used SQL Server 2014.

  1. USEMASTER  
  2. GO  
  3.   
  4. -- 1) Check for the Database Exists .If the database is exist then drop and create new DB   
  5. IFEXISTS(SELECT [name] FROMsys.databasesWHERE [name] ='ItemsDB')  
  6. DROPDATABASEItemsDB  
  7. GO  
  8.   
  9. CREATEDATABASEItemsDB  
  10. GO  
  11.   
  12. USEItemsDB  
  13. GO  
  14.   
  15.   
  16. -- 1) //////////// Item Masters   
  17.   
  18. IFEXISTS(SELECT [name] FROMsys.tablesWHERE [name] ='ItemMaster')  
  19. DROPTABLEItemMaster  
  20. GO  
  21.   
  22. CREATETABLE [dbo].[ItemMaster](  
  23. [ItemID] INTIDENTITYPRIMARYKEY,  
  24. [ItemName] [varchar](100)NOTNULL,  
  25. [SaleCount] [varchar](10)NOTNULL  
  26. )  
  27.   
  28. -- insert sample data to Item Master table   
  29. INSERTINTOItemMaster([ItemName],[SaleCount])  
  30. VALUES ('Item1','100')  
  31.   
  32. INSERTINTOItemMaster([ItemName],[SaleCount])  
  33. VALUES ('Item2','82')  
  34.   
  35. INSERTINTOItemMaster([ItemName],[SaleCount])  
  36. VALUES ('Item3','98')  
  37.   
  38. INSERTINTOItemMaster([ItemName],[SaleCount])  
  39. VALUES ('Item4','34')  
  40.   
  41. INSERTINTOItemMaster([ItemName],[SaleCount])  
  42. VALUES ('Item5','68')  
  43.   
  44. select*fromItemMaster  
  45.   
  46.   
  47. -- 1)To Select Item Details   
  48.   
  49. -- Author : Shanu   
  50. -- Create date : 2016-03-15   
  51. -- Description :To Select Item Details   
  52. -- Tables used :ItemMaster  
  53. -- Modifier : Shanu   
  54. -- Modify date : 2016-03-15   
  55. -- =============================================   
  56. -- To Select Item Details  
  57. -- EXEC USP_Item_Select ''  
  58. -- =============================================   
  59. CREATEPROCEDURE [dbo].[USP_Item_Select]   
  60. (  
  61. @ItemName VARCHAR(100)=''   
  62. )  
  63. AS  
  64. BEGIN   
  65. SELECTItemName,  
  66. SaleCount  
  67. FROMItemMaster  
  68. WHERE  
  69. ItemNamelike @ItemName+'%'  
  70. OrderBYItemName  
  71. END  
  72. GO   
  73.   
  74.   
  75.   
  76. -- 2) To Insert/Update Item Details   
  77.   
  78. -- Author : Shanu   
  79. -- Create date : 2016-03-15   
  80. -- Description :To Insert/Update Item Details   
  81. -- Tables used :ItemMaster  
  82. -- Modifier : Shanu   
  83. -- Modify date : 2016-03-15   
  84. -- =============================================   
  85. -- To Insert/Update Item Details  
  86. -- EXEC USP_Item_Edit ''  
  87. -- =============================================   
  88. CREATEPROCEDURE [dbo].[USP_Item_Edit]   
  89. (  
  90. @ItemName VARCHAR(100)='',  
  91. @SaleCount VARCHAR(10)=''  
  92.   
  93. )  
  94. AS  
  95. BEGIN   
  96. IFNOTEXISTS(SELECT*FROMItemMasterWHEREItemName=@ItemName)  
  97. BEGIN  
  98.   
  99. INSERTINTOItemMaster([ItemName],[SaleCount])  
  100. VALUES (@ItemName,@SaleCount)  
  101.   
  102. Select'Inserted'as results  
  103. return;  
  104. END  
  105. ELSE  
  106. BEGIN  
  107. UpdateItemMasterSET  
  108. SaleCount=@SaleCount  
  109. WHEREItemName=@ItemName  
  110. Select'Updated'as results  
  111. return;  
  112. END  
  113. Select'Error'as results  
  114. END  
  115.   
  116.   
  117. -- 3)To Max and Min Value  
  118.   
  119. -- Author : Shanu   
  120. -- Create date : 2016-03-15   
  121. -- Description :To Max and Min Value   
  122. -- Tables used :ItemMaster  
  123. -- Modifier : Shanu   
  124. -- Modify date : 2016-03-15   
  125. -- =============================================   
  126. -- To Max and Min Value  
  127. -- EXEC USP_ItemMaxMin_Select ''  
  128. -- =============================================   
  129. CREATEPROCEDURE [dbo].[USP_ItemMaxMin_Select]   
  130. (  
  131. @ItemName VARCHAR(100)=''   
  132. )  
  133. AS  
  134. BEGIN   
  135. SELECTMIN(convert(int,SaleCount))asMinValue,  
  136. MAX(convert(int,SaleCount))asMaxValue   
  137. FROMItemMaster  
  138. WHERE  
  139. ItemNamelike @ItemName+'%'  
  140.   
  141. END  
  142. GO   
Step 2 : Create your MVC Web Application in Visual Studio 2015

After installing our Visual Studio 2015 click Start, then Programs and select Visual Studio 2015 - Click Visual Studio 2015. Click New, then Project, select Web and then select ASP.NET Web Application. Enter your project name and click OK.

project

Select MVC, WEB API and click OK.

mvc

Now we have created our MVC Application as a next step we add our SQL server database as Entity Data Model to our application.

Add Database using ADO.NET Entity Data Model
Right click our project and click Add -> New Item.
Select Data->Select ADO.NET Entity Data Model> Give the name for our EF and click Add

add

Select EF Designer from database and click next.

EF Designer

Here click New Connection and provide your SQL-Server Server Name and connect to your database.

Here we can see we have given our SQL server name, Id and PWD and after it connectedwe have selected the data base as ItemsDB as we have created the Database using my SQL Script.

server

Click next and select our tables need to be used and click finish.

finish

Here we can see we have selected our table ItemMasters and all needed Stored Procedures after selecting click Finish,

table

Once Entity has been created, the next step is we add WEB API to our controller and write function to select/Insert/Update and Delete.

Steps to add our WEB API Controller

Right Click Controllers folder-> Click Add-> Click Controller.

As we are going to create our WEB API Controller.Select Controller and Add Empty WEB API 2 Controller. Give your Name to Web API controller and click ok. Here for my Web API Controller I have given name as “StudentsController”.

add

As we all know Web API is a simple and easy to build HTTP Services for Browsers and Mobiles, Web API has four methods as Get/Post/Put and Deletewhere, 
  • Get is to request for the data. (Select).
  • Post is to create a data. (Insert).
  • Put is to update the data.
  • Delete is to delete data.
In our example we will use both Get and Post as we need to get all image names and descriptions from database and to insert new Image Name and Image Description to database.

Get Method

In our example I have used only Get method as I am using only Stored Procedure. We need to create object for our Entity and write our Get Method to perform Select/Insert/Update and Delete operations.

Select Operation

We use get Method to get all the details of itemMaster table using entity object and we return the result as IEnumerable .We use this method in our AngularJS and bind the result in ComboBox and insert the new chart Item to Database using the Insert Method.
  1. publicclassItemAPIController: ApiController  
  2. {  
  3.     ItemsDBEntitiesobjapi = newItemsDBEntities();  
  4.   
  5.     // To get all Item chart detaiuls  
  6.     [HttpGet]  
  7.     publicIEnumerable < USP_Item_Select_Result > getItemDetails(stringItemName)  
  8.     {  
  9.         if (ItemName == null)  
  10.             ItemName = "";  
  11.         returnobjapi.USP_Item_Select(ItemName).AsEnumerable();  
  12.     }  
  13.   
  14.     // To get maximum and Minimum value  
  15.     [HttpGet]  
  16.     publicIEnumerable < USP_ItemMaxMin_Select_Result > getItemMaxMinDetails(stringItemNM)  
  17.     {  
  18.         if (ItemNM == null)  
  19.             ItemNM = "";  
  20.         returnobjapi.USP_ItemMaxMin_Select(ItemNM).AsEnumerable();  
  21.     }  
  22.   
  23.     // To Insert/Update Item Details  
  24.     [HttpGet]  
  25.     publicIEnumerable < string > insertItem(stringitemName, stringSaleCount)  
  26.     {  
  27.         returnobjapi.USP_Item_Edit(itemName, SaleCount).AsEnumerable();  
  28.     }  
  29.   
  30. }  
Now we have created our Web API Controller Class. Next step we need to create our AngularJs Module and Controller. Let’s see how to create our AngularJS Controller. In Visual Studio 2015 it’s much easy to add our AngularJsController. Let’s see step by Step on how to create and write our AngularJs Controller.

Creating AngularJS Controller

First create a folder inside the Script Folder and we give the folder name as “MyAngular”.

First create a folder inside the Script Folder and Igiven the folder name as “MyAngular”.

Now add your Angular Controller inside the folder.

Right Click the MyAngular Folder and click Add and New Item > Select Web > Select AngularJs Controller and give name to Controller.We have given my AngularJs Controller as “Controller.js”.

new item

If the Angular JS package is missing then add the package to your project.

Right Click your MVC project and Click-> Manage NuGet Packages. Search for AngularJs and click Install.

install

Modules.js:

Here we will add the reference to the AngularJS JavaScript and create an Angular Module named “AngularJs_Module”.
  1. // <reference path="../angular.js" />  
  2. /// <reference path="../angular.min.js" />  
  3. /// <reference path="../angular-animate.js" />  
  4. /// <reference path="../angular-animate.min.js" />  
  5. var app;  
  6. (function () {  
  7. app = angular.module("AngularJs_Module", ['ngAnimate']);  
  8. })();  
Controllers:

In AngularJS Controller I have done all the business logic and returned the data from Web API to our MVC HTML page.
  1. Variable declarations

    Firstly, we declared all the local variables need to be used.
    1. app.controller("AngularJs_Controller", function ($scope, $timeout, $rootScope, $window, $http, FileUploadService) {  
    2. $scope.date = newDate();  
    3. // <reference path="../angular.js" />  
    4. /// <reference path="../angular.min.js" />  
    5. /// <reference path="../angular-animate.js" />  
    6. /// <reference path="../angular-animate.min.js" />  
    7. var app;  
    8. (function () {  
    9. app = angular.module("RESTClientModule", ['ngAnimate']);  
    10. })();  
    11.   
    12.   
    13. app.controller("AngularJs_Controller", function ($scope, $timeout, $rootScope, $window, $http) {  
    14. $scope.date = newDate();  
    15. $scope.MyName = "shanu";  
    16. $scope.sItemName = "";  
    17. $scope.itemCount = 5;  
    18. $scope.selectedItem = "";  
    19. $scope.chartTitle = "SHANU Donut Chart";  
    20. $scope.waterMark = "SHANU";  
    21. $scope.ItemValues = 0;  
    22. $scope.ItemNames = "";  
    23. $scope.showItemAdd = false;  
    24.   
    25. $scope.minsnew = 0;  
    26. $scope.maxnew =0;  
  2. Methods

    Select Method

    method

    Here we get all the data from WEB API and bind the result to our ComboBox and we have used another method to get the maximum and Minimum Value of Chart Value and bind in hidden field.
    1. // This method is to get all the Item Details to bind in Combobox for plotting in Graph  
    2. selectuerRoleDetails($scope.sItemName);  
    3. // This method is to get all the Item Details to bind in Combobox for plotting in Graph  
    4. functionselectuerRoleDetails(ItemName)   
    5. {  
    6.     $http.get('/api/ItemAPI/getItemDetails/',  
    7.      {  
    8.             params:  
    9.             {  
    10.                 ItemName: ItemName  
    11.             }  
    12.         }).success(function(data)  
    13.          {  
    14.             $scope.itemData = data;  
    15.             $scope.itemCount = $scope.itemData.length;  
    16.             $scope.selectedItem = $scope.itemData[0].SaleCount;  
    17.   
    18.         })  
    19.         .error(function()   
    20.         {  
    21.             $scope.error = "An Error has occured while loading posts!";  
    22.         });  
    23.   
    24.     $http.get('/api/ItemAPI/getItemMaxMinDetails/',  
    25.        {  
    26.             params:  
    27.             {  
    28.                 ItemNM: $scope.sItemName  
    29.             }  
    30.         }).success(function(data)  
    31.         {  
    32.             $scope.itemDataMaxMin = data;  
    33.             $scope.minsnew = $scope.itemDataMaxMin[0].MinValue;  
    34.             $scope.maxnew = $scope.itemDataMaxMin[0].MaxValue;  
    35.   
    36.   
    37.         })  
    38.         .error(function()  
    39.         {  
    40.             $scope.error = "An Error has occured while loading posts!";  
    41.         });  
    42.   
    43. }  
    Insert Method

    User can Insert or update Chart Item value by clicking Add Chart Item Details. After validation we pass the Chart Item name and Value to WEB API method to insert in to our database.

    insert
    1. //Save File  
    2. $scope.saveDetails = function()  
    3. {  
    4.   
    5. $scope.IsFormSubmitted = true;  
    6.   
    7. $scope.Message = "";  
    8. if ($scope.ItemNames == "")  
    9. {  
    10.     alert("Enter Item Name");  
    11.     return;  
    12. }  
    13.   
    14. if ($scope.ItemValues == "")  
    15. {  
    16.     alert("Enter Item Value");  
    17.     return;  
    18. }  
    19.   
    20.   
    21.   
    22. if ($scope.IsFormValid)  
    23. {  
    24.     alert($scope.ItemNames);  
    25.     $http.get('/api/ItemAPI/insertItem/',  
    26.     {  
    27.             params:  
    28.             {  
    29.                 itemName: $scope.ItemNames,  
    30.                 SaleCount: $scope.ItemValues  
    31.             }  
    32.         }).success(function(data)  
    33.          {  
    34.   
    35.             $scope.CharDataInserted = data;  
    36.             alert($scope.CharDataInserted);  
    37.   
    38.             cleardetails();  
    39.             selectuerRoleDetails($scope.sItemName);  
    40.         })  
    41.         .error(function()  
    42.         {  
    43.             $scope.error = "An Error has occured while loading posts!";  
    44.         });  
    45. else  
    46. {  
    47.     $scope.Message = "All the fields are required.";  
    48. }  
    49.   
    50. };  
    51.   
    52. });  

Step 3: Todraw our Chart using JQuery to our MVC page Canvas Tag

Herewe will see in detail about how to draw our Donut Chart on our MVC Web Application using JQuery.
Inside the java Script 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 Chart category colors to array .Here we have fixed to 12 colors and 12 data’s to add with Donut Chart. If you want you can add more from here. Here we have 2 set of color combination one with Green base and one with Blue base. User can add as per your requirement here.

  1. varpirChartColor = ["#6CBB3C""#F87217""#EAC117""#EDDA74""#CD7F32""#CCFB5D""#FDD017""#9DC209""#E67451""#728C00""#617C58""#64E986"]; // green Color Combinations  
  2. // varpirChartColor = ["#3090C7", "#BDEDFF", "#78C7C7", "#736AFF", "#7FFFD4", "#3EA99F", "#EBF4FA", "#F9B7FF", "#8BB381", "#BDEDFF", "#B048B5", "#4E387E"]; // Blue Color Combinations  
  3.   
  4. //This method will be used to check for user selected Color Theme and Change the color  
  5. functionChangeChartColor()   
  6. {  
  7.   
  8.     if ($('#rdoColorGreen:checked').val() == "Green Theme")   
  9.     {  
  10.         pirChartColor = ["#6CBB3C""#F87217""#EAC117""#EDDA74""#CD7F32""#CCFB5D""#FDD017""#9DC209""#E67451""#728C00""#617C58""#64E986"]; // green Color Combinations  
  11.         lineColor = "#3090C7"// Blue Color for Line  
  12.         lineOuterCircleColor = "#6CBB3C"// Green Color for Outer Circle  
  13.   
  14.     } else   
  15.     {  
  16.         pirChartColor = ["#3090C7""#BDEDFF""#78C7C7""#736AFF""#7FFFD4""#3EA99F""#EBF4FA""#F9B7FF""#8BB381""#BDEDFF""#B048B5""#4E387E"]; // Blue Color Combinations  
  17.         lineColor = "#F87217"// Orange Color for the Line  
  18.         lineOuterCircleColor = "#F70D1A "// Red Color for the outer circle  
  19.     }  
  20. }  
Method to get X plot and Y Plot Value: here we calculate to draw our Chart item in X and in Y Axis.
  1. // to return the x-Value  
  2. functiongetXPlotvalue(val)  
  3. {  
  4.   
  5.     return (Math.round((chartWidth) / noOfPlots)) * val + (xSpace * 1.5) - 20;  
  6. }  
  7.   
  8. // Return the y value  
  9. functiongetYPlotVale(val)  
  10. {  
  11.     returnchartHeight - (((chartHeight - xSpace) / maxDataVal) * val);  
  12.   
  13. }  
Draw Legend:

If the Show Legend radio button is clicked then we draw a Legend for our Chart item inside Canvas Tag and also in this method we check to display Alert Image or not.
  1. // This function is used to draw the Legend  
  2. functiondrawLengends()  
  3. {  
  4.     ctx.fillStyle = "#7F462C";  
  5.     ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);  
  6.     //Drawing Inner White color Rectange with in Above brown rectangle to plot all the Lables with color,Text and Value.  
  7.     ctx.fillStyle = "#FFFFFF";  
  8.     rectInner.startX = rect.startX + 1;  
  9.     rectInner.startY = rect.startY + 1;  
  10.     rectInner.w = rect.w - 2;  
  11.     rectInner.h = rect.h - 2;  
  12.     ctx.fillRect(rectInner.startX, rectInner.startY, rectInner.w, rectInner.h);  
  13.   
  14.   
  15.     labelBarX = rectInner.startX + 4;  
  16.     labelBarY = rectInner.startY + 4;  
  17.     labelBarWidth = rectInner.w - 10;  
  18.     labelBarHeight = (rectInner.h / noOfPlots) - 5;  
  19.     colorval = 0;  
  20.     // here to draw all the rectangle for Lables with Image display  
  21.     $('#DropDownList1 option').each(function()  
  22.       {  
  23.         ctx.fillStyle = pirChartColor[colorval];  
  24.   
  25.         ctx.fillRect(labelBarX, labelBarY, labelBarWidth, labelBarHeight);  
  26.         // Here we check for the rdoAlert Status is On - If the Alert is on then we display the Alert Image as per the Alert check value.  
  27.         if ($('#rdoAlaramOn:checked').val() == "Alert On")   
  28.         {  
  29.             // Here we can see fo ever chart value we check with the condition .we have initially declare the alertCheckValue as 300.  
  30.             //so if the Chart Plot value is Greater then or equal to the check value then we display the Green Image else we display the Red Image.  
  31.             //user can change this to your requiremnt if needed.This is optioan function for the Pie Chart.  
  32.             if (parseInt($(this).val()) >= alertCheckValue)   
  33.             {  
  34.                 ctx.drawImage(greenImage, labelBarX, labelBarY + (labelBarHeight / 3) - 4, imagesize, imagesize);  
  35.             } else  
  36.             {  
  37.                 ctx.drawImage(redImage, labelBarX, labelBarY + (labelBarHeight / 3) - 4, imagesize, imagesize);  
  38.             }  
  39.         }  
  40.         //Draw the Donut Chart Label text and Value  
  41.         ctx.fillStyle = "#000000";  
  42.         ctx.font = '10pt Calibri';  
  43.         ctx.fillText($(this).text(), labelBarX + imagesize + 2, labelBarY + (labelBarHeight / 2));  
  44.   
  45.         // To Increment and draw the next bar ,label Text and Alart Image.  
  46.   
  47.         labelBarY = labelBarY + labelBarHeight + 4;  
  48.         // labelTextYXVal = labelBarY + labelBarHeight - 4;  
  49.   
  50.         colorval = colorval + 1;  
  51.   
  52.     });  
  53. }  
Draw Chart:

This is our main Function .Here we get all the details to draw our Donut Chart. In this function we will draw Chart Title, Chart Water Mark text, Chart Logo Image and finally call draw donut chart Method to draw our Donut chart inside Canvas Tag.
  1. // This is the main function to darw the Charts  
  2. functiondrawChart()  
  3. {  
  4.   
  5.     ChangeChartColor();  
  6.   
  7.     // asign the images path for both Alert images  
  8.     greenImage.src = '../images/Green.png';  
  9.     redImage.src = '../images/Red.png';  
  10.   
  11.     LogoImage.src = '../images/shanu.jpg';  
  12.   
  13.     // Get the minumum and maximum value.herei have used the hidden filed from code behind wich will stored the Maximum and Minimum value of the Drop down list box.  
  14.   
  15.     minDataVal = $('input:text[name=hidListMin]').val();  
  16.     maxDataVal = $('input:text[name=hidListMax]').val();  
  17.   
  18.     // Total no of plots we are going to draw.  
  19.     noOfPlots = $("#DropDownList1 option").length;  
  20.   
  21.     maxValdivValue = Math.round((maxDataVal / noOfPlots));  
  22.   
  23.   
  24.     //storing the Canvas Context to local variable ctx.This variable will be used to draw the Pie Chart  
  25.     canvas = document.getElementById("canvas");  
  26.     ctx = canvas.getContext("2d");  
  27.     //globalAlpha - > is used to display the 100% opoacity of chart .because at the bottom of the code I have used the opacity to 0.1 to display the water mark text with fade effect.  
  28.     ctx.globalAlpha = 1;  
  29.     ctx.fillStyle = "#000000";  
  30.     ctx.strokeStyle = '#000000';  
  31.     //Every time we clear the canvas and draw the chart  
  32.     ctx.clearRect(0, 0, canvas.width, canvas.height);  
  33.   
  34.     //If need to draw without legend for the PIE Chart  
  35.     chartWidth = canvas.width - xSpace;  
  36.     chartHeight = canvas.height - ySpace;  
  37.   
  38.   
  39.     // step 1) Draw legend $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$########################  
  40.     if ($('#chkLegend:checked').val() == "Show Legend")  
  41.     {  
  42.   
  43.         chartWidth = canvas.width - ((canvas.width / 3) - (xSpace / 2));  
  44.         chartHeight = canvas.height - ySpace - 10;  
  45.   
  46.         legendWidth = canvas.width - ((canvas.width / 3) - xSpace);  
  47.         legendHeight = ySpace;  
  48.   
  49.         rect.startX = legendWidth;  
  50.         rect.startY = legendHeight;  
  51.         rect.w = canvas.width / 3 - xSpace - 10;  
  52.         rect.h = canvas.height - ySpace - 10;  
  53.   
  54.         //In this method i will draw the legend with the Alert Image.  
  55.         drawLengends();  
  56.   
  57.     }  
  58.     // end step 1) $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$  
  59.   
  60.     varchartMidPosition = chartWidth / 2 - 60;  
  61.   
  62.     //// //If need to draw with legend  
  63.     //// chartWidth = canvas.width - ((canvas.width / 3) - (xSpace / 2));  
  64.     //// chartHeight = canvas.height - ySpace - 10;  
  65.   
  66.   
  67.     // Step 2 ) +++++++++++++ To Add Chart Titel and Company Logo  
  68.     //To Add Logo to Chart  
  69.   
  70.   
  71.   
  72.     varlogoXVal = canvas.width - LogoImgWidth - 10;  
  73.     varlogolYVal = 0;  
  74.   
  75.     //here we draw the Logo for teh chart and i have used the alpha to fade and display the Logo.  
  76.     ctx.globalAlpha = 0.6;  
  77.   
  78.     ctx.drawImage(LogoImage, logoXVal, logolYVal, LogoImgWidth, LogoImgHeight);  
  79.   
  80.     ctx.globalAlpha = 1;  
  81.   
  82.     ctx.font = '22pt Calibri';  
  83.     ctx.fillStyle = "#15317E";  
  84.   
  85.     vartitletxt = $('input:text[name=txtTitle]').val();  
  86.   
  87.     ctx.fillText(titletxt, chartMidPosition, chartHeight + 60);  
  88.   
  89.   
  90.     ctx.fillStyle = "#000000";  
  91.     ctx.font = '10pt Calibri';  
  92.   
  93.     // end step 2) +++++++++++ End of Title and Company Logo Add  
  94.   
  95.     // Step 3 ) +++++++++++++ toDraw the X-Axis and Y-Axis  
  96.   
  97.     // >>>>>>>>> Draw Y-Axis and X-Axis Line(Horizontal Line)  
  98.     // Draw the axises  
  99.     //////ctx.beginPath();  
  100.     //////ctx.moveTo(xSpace, ySpace);  
  101.     //////// first Draw Y Axis  
  102.     //////ctx.lineTo(xSpace, chartHeight);  
  103.   
  104.     //////// Next draw the X-Axis  
  105.     //////ctx.lineTo(chartWidth, chartHeight);  
  106.     //////ctx.stroke();  
  107.     // >>>>>>>>>>>>> End of X-Axis PIE Draw  
  108.     //end step 3) +++++++++++++++++++++++  
  109.   
  110.   
  111.     // Step 4) <<<<<<<<<<<<<<<<<<<<<<< To Draw X - Axis Plot Values <<<<<<<<<<<<< }}}}}}  
  112.     // Draw the X value texts  
  113.     // --->>>>>>>>>>>> for the Bar Chart i have draw the X-Axis plot in with drawBarChart  
  114.     // <<<<<<<<<<<<<<<<<<<<<<< End of X Axis Draw  
  115.   
  116.     // end Step 4) <<<<<<<<<<<<<<<<<<<<<<<  
  117.   
  118.   
  119.     // Step 5){{{{{{{{{{{{  
  120.     // {{{{{{{{{{{{{To Draw the Y Axis Plot Values}}}}}}}}}}}}}}  
  121.   
  122.     ////////varvAxisPoints = 0;  
  123.     ////////var max = maxDataVal;  
  124.     ////////max += 10 - max % 10;  
  125.     ////////for (vari = 0; i<= maxDataVal; i += maxValdivValue) {  
  126.   
  127.     //////// ctx.fillStyle = fotnColor;  
  128.     //////// ctx.font = axisfontSize + 'pt Calibri';  
  129.     //////// ctx.fillText(i, xSpace - 40, getYPlotVale(i));  
  130.   
  131.     //////// //Here we draw the Y-Axis point PIE  
  132.     //////// ctx.beginPath();  
  133.     //////// ctx.moveTo(xSpace, getYPlotVale(i));  
  134.   
  135.     //////// ctx.lineTo(xSpace - 10, getYPlotVale(i));  
  136.     //////// ctx.stroke();  
  137.     //////// vAxisPoints = vAxisPoints + maxValdivValue;  
  138.   
  139.   
  140.     ////////}  
  141.   
  142.     //}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}  
  143.   
  144.     //Step 5) *********************************************************  
  145.     //Function to Draw our Chart here we can Call/Bar Chart/PIE Chart or Pie Chart  
  146.   
  147.     drawDonutChart();  
  148.   
  149.     // end step 6) **************  
  150.   
  151.     //Step 7) :::::::::::::::::::: to add the Water mark Text  
  152.     varwaterMarktxt = $('input:text[name=txtWatermark]').val();  
  153.   
  154.   
  155.     // Here add the Water mark text at center of the chart  
  156.     ctx.globalAlpha = 0.1;  
  157.     ctx.font = '86pt Calibri';  
  158.     ctx.fillStyle = "#000000";  
  159.     ctx.fillText(waterMarktxt, chartMidPosition - 40, chartHeight / 2);  
  160.   
  161.     ctx.font = '10pt Calibri';  
  162.     ctx.globalAlpha = 1;  
  163.     /// end step 7) ::::::::::::::::::::::::::::::::::::::  
  164.   
  165. }  
DrawDonutChart:In this function we get all item names and value usingforeachof ComboBoxand here we plot all value and draw Donut chart using the ComboBoxvalues. First we will get total of all values from the getChartTotal() Method. We will be using this total value to calculate and draw our Donut Chart.
  1. functiondrawDonutChart()  
  2. {  
  3.   
  4.     varlastend = 0;  
  5.     varXvalPosition = xSpace;  
  6.   
  7.     chartWidth = (canvas.width / 2) - xSpace;  
  8.     chartHeight = (canvas.height / 2) - (xSpace / 2);  
  9.   
  10.     widthcalculation = parseInt(((parseInt(chartWidth) - 100) / noOfPlots));  
  11.   
  12.     vardonutOutercircle = chartHeight / 2;  
  13.     vardonutinnersircle = (chartWidth / 2) + xSpace;  
  14.   
  15.   
  16.     colorval = 0;  
  17.     varchartTotalResult = getChartTotal();  
  18.   
  19.     var legend1 = 0;  
  20.     $('#DropDownList1 option').each(function()  
  21.     {  
  22.   
  23.         ctx.fillStyle = pirChartColor[colorval];  
  24.         legend1 += (Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult))  
  25.             //----  
  26.         ctx.beginPath();  
  27.         ctx.moveTo(chartWidth, chartWidth);  
  28.         ctx.arc(chartWidth, chartWidth, donutOutercircle, lastend, legend1, false); // Outer: CCW  
  29.         ctx.arc(chartWidth, chartWidth, donutinnersircle, legend1, lastend, true); // Inner: CW  
  30.         //------  
  31.   
  32.         ctx.fill();  
  33.         lastend += Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult);  
  34.   
  35.         //END Draw Bar Graph **************==================********************  
  36.         colorval = colorval + 1;  
  37.     });  
  38.   
  39.   
  40. }  
  41.   
  42. functiongetChartTotal()  
  43. {  
  44.     varchartTotalResult = 0;  
  45.     $('#DropDownList1 option').each(function()  
  46.      {  
  47.   
  48.         chartTotalResult += (typeofparseInt($(this).val()) == 'number') ? parseInt($(this).val()) : 0;  
  49.     });  
  50.   
  51.     return chartTotalResult;  
Note:

Run the SQL Script in your SQL Server to created DB, Table and stored procedure. Inweb.config change the connection string to your local SQL Server connection. In the attached zip file you can find code for both Bar, Line,Pie, Bar& Line and Donut Chart.

Tested Browsers: 
  • Chrome
  • Firefox
  • IE10
Read more articles on ASP.NET:


Similar Articles