Introduction

In our previous article we have seen in detail how to draw Bar and Line Chart in MVC web Application. In this article we will see how to draw Pie 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

  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. (You can redesign and customize as per your requirement if needed).
  4. Chart Water Mark Text:

    In some cases we need to add our Company name as watermark to our Chart. Here in our example we will draw the watermark Textbox text at the center of the Chart. (You can redesign and customize as per your requirement if needed).
  5. Chart Company LOGO:

    User can add own Company logo to the Chart. (Here for sample we have added own image as a Logo at the top left corner. (You can redesign and customize as per your requirement 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 their requirement and add 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 output here. User can also add any number of themes as they require.

Blue Theme

Green Theme

In this article we have 2 parts,

Prerequisites

Visual Studio 2015: You can download it from here .

Code Part

In code part we can see the following three 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 an ItemMaster 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. USE MASTER
  2. GO
  3. -- 1) Check for the Database Exists .If the database is exist then drop and create new DB
  4. IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'ItemsDB' )
  5. DROP DATABASE ItemsDB
  6. GO
  7. CREATE DATABASE ItemsDB
  8. GO
  9. USE ItemsDB
  10. GO
  11. -- 1) //////////// Item Masters
  12. IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'ItemMaster' )
  13. DROP TABLE ItemMaster
  14. GO
  15. CREATE TABLE [dbo].[ItemMaster](
  16. [ItemID] INT IDENTITY PRIMARY KEY,
  17. [ItemName] [varchar](100) NOT NULL,
  18. [SaleCount] [varchar](10) NOT NULL
  19. )
  20. -- insert sample data to Item Master table
  21. INSERT INTO ItemMaster ([ItemName],[SaleCount])
  22. VALUES ('Item1','100')
  23. INSERT INTO ItemMaster ([ItemName],[SaleCount])
  24. VALUES ('Item2','82')
  25. INSERT INTO ItemMaster ([ItemName],[SaleCount])
  26. VALUES ('Item3','98')
  27. INSERT INTO ItemMaster ([ItemName],[SaleCount])
  28. VALUES ('Item4','34')
  29. INSERT INTO ItemMaster ([ItemName],[SaleCount])
  30. VALUES ('Item5','68')
  31. select * from ItemMaster
  32. -- 1)To Select Item Details
  33. -- Author : Shanu
  34. -- Create date : 2016-03-15
  35. -- Description :To Select Item Details
  36. -- Tables used : ItemMaster
  37. -- Modifier : Shanu
  38. -- Modify date : 2016-03-15
  39. -- =============================================
  40. -- To Select Item Details
  41. -- EXEC USP_Item_Select ''
  42. -- =============================================
  43. CREATE PROCEDURE [dbo].[USP_Item_Select]
  44. (
  45. @ItemName VARCHAR(100) = ''
  46. )
  47. AS
  48. BEGIN
  49. SELECT ItemName,
  50. SaleCount
  51. FROM ItemMaster
  52. WHERE
  53. ItemName like @ItemName +'%'
  54. Order BY ItemName
  55. END
  56. GO
  57. -- 2) To Insert/Update Item Details
  58. -- Author : Shanu
  59. -- Create date : 2016-03-15
  60. -- Description :To Insert/Update Item Details
  61. -- Tables used : ItemMaster
  62. -- Modifier : Shanu
  63. -- Modify date : 2016-03-15
  64. -- =============================================
  65. -- To Insert/Update Item Details
  66. -- EXEC USP_Item_Edit ''
  67. -- =============================================
  68. CREATE PROCEDURE [dbo].[USP_Item_Edit]
  69. (
  70. @ItemName VARCHAR(100) = '',
  71. @SaleCount VARCHAR(10) = ''
  72. )
  73. AS
  74. BEGIN
  75. IF NOT EXISTS (SELECT * FROM ItemMaster WHERE ItemName=@ItemName)
  76. BEGIN
  77. INSERT INTO ItemMaster ([ItemName],[SaleCount])
  78. VALUES (@ItemName,@SaleCount)
  79. Select 'Inserted' as results
  80. return;
  81. END
  82. ELSE
  83. BEGIN
  84. Update ItemMaster SET
  85. SaleCount=@SaleCount
  86. WHERE ItemName=@ItemName
  87. Select 'Updated' as results
  88. return;
  89. END
  90. Select 'Error' as results
  91. END
  92. -- 3)To Max and Min Value
  93. -- Author : Shanu
  94. -- Create date : 2016-03-15
  95. -- Description :To Max and Min Value
  96. -- Tables used : ItemMaster
  97. -- Modifier : Shanu
  98. -- Modify date : 2016-03-15
  99. -- =============================================
  100. -- To Max and Min Value
  101. -- EXEC USP_ItemMaxMin_Select ''
  102. -- =============================================
  103. CREATE PROCEDURE [dbo].[USP_ItemMaxMin_Select]
  104. (
  105. @ItemName VARCHAR(100) = ''
  106. )
  107. AS
  108. BEGIN
  109. SELECT MIN(convert(int,SaleCount)) as MinValue,
  110. MAX(convert(int,SaleCount)) as MaxValue
  111. FROM ItemMaster
  112. WHERE
  113. ItemName like @ItemName +'%'
  114. END
  115. GO
Step 2: Create your MVC Web Application in Visual Studio 2015

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

Select MVC, Web API and click OK.

Now we have created our MVC Application and 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, then New Item.

Select Data, ADO.NET Entity Data Model and then give the name for our EF and click Add

Select EF Designer from database and click next.

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

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

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

Once Entity has been created, next step 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 and then 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.

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 Delete where,

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 name 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. public class ItemAPIController : ApiController
  2. {
  3. ItemsDBEntities objapi = new ItemsDBEntities();
  4. // To get all Item chart detaiuls
  5. [HttpGet]
  6. public IEnumerable<USP_Item_Select_Result> getItemDetails(string ItemName)
  7. {
  8. if (ItemName == null)
  9. ItemName = "";
  10. return objapi.USP_Item_Select(ItemName).AsEnumerable();
  11. }
  12. // To get maximum and Minimum value
  13. [HttpGet]
  14. public IEnumerable<USP_ItemMaxMin_Select_Result> getItemMaxMinDetails(string ItemNM)
  15. {
  16. if (ItemNM == null)
  17. ItemNM = "";
  18. return objapi.USP_ItemMaxMin_Select(ItemNM).AsEnumerable();
  19. }
  20. // To Insert/Update Item Details
  21. [HttpGet]
  22. public IEnumerable<string> insertItem(string itemName, string SaleCount)
  23. {
  24. return objapi.USP_Item_Edit(itemName,SaleCount).AsEnumerable();
  25. }
  26. }
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 AngularJS Controller. Let’s see step by step on how to create and write our AngularJS Controller.

Creating AngularJS Controller

Firstly, create a folder inside the Script Folder and give the folder name as “MyAngular”

Now add your Angular Controller inside the folder.

Right Click the MyAngular Folder and click Add and New Item, then select Web and then AngularJS Controller and give name to Controller. We have given my AngularJS Controller as “controller.js”

If the AngularJS 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.

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 = new Date();
  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. app.controller("AngularJs_Controller", function ($scope, $timeout, $rootScope, $window, $http) {
  12. $scope.date = new Date();
  13. $scope.MyName = "shanu";
  14. $scope.sItemName = "";
  15. $scope.itemCount = 5;
  16. $scope.selectedItem = "";
  17. $scope.chartTitle = "SHANU Line Chart";
  18. $scope.waterMark = "SHANU";
  19. $scope.ItemValues = 0;
  20. $scope.ItemNames = "";
  21. $scope.showItemAdd = false;
  22. $scope.minsnew = 0;
  23. $scope.maxnew =0;

2. Methods

Select 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. function selectuerRoleDetails(ItemName) {
  5. $http.get('/api/ItemAPI/getItemDetails/', { params: { ItemName: ItemName } }).success(function (data) {
  6. $scope.itemData = data;
  7. $scope.itemCount = $scope.itemData.length;
  8. $scope.selectedItem = $scope.itemData[0].SaleCount;
  9. })
  10. .error(function () {
  11. $scope.error = "An Error has occured while loading posts!";
  12. });
  13. $http.get('/api/ItemAPI/getItemMaxMinDetails/', { params: { ItemNM: $scope.sItemName } }).success(function (data) {
  14. $scope.itemDataMaxMin = data;
  15. $scope.minsnew = $scope.itemDataMaxMin[0].MinValue;
  16. $scope.maxnew = $scope.itemDataMaxMin[0].MaxValue;
  17. })
  18. .error(function () {
  19. $scope.error = "An Error has occured while loading posts!";
  20. });
  21. }

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.



  1. //Save File
  2. $scope.saveDetails = function () {
  3. $scope.IsFormSubmitted = true;
  4. $scope.Message = "";
  5. if ($scope.ItemNames == "")
  6. {
  7. alert("Enter Item Name");
  8. return;
  9. }
  10. if ($scope.ItemValues == "") {
  11. alert("Enter Item Value");
  12. return;
  13. }
  14. if ($scope.IsFormValid) {
  15. alert($scope.ItemNames);
  16. $http.get('/api/ItemAPI/insertItem/', { params: { itemName: $scope.ItemNames, SaleCount: $scope.ItemValues } }).success(function (data) {
  17. $scope.CharDataInserted = data;
  18. alert($scope.CharDataInserted);
  19. cleardetails();
  20. selectuerRoleDetails($scope.sItemName);
  21. })
  22. .error(function () {
  23. $scope.error = "An Error has occured while loading posts!";
  24. });
  25. }
  26. else {
  27. $scope.Message = "All the fields are required.";
  28. }
  29. };
  30. });
Step 3: To draw our Chart using JQuery to our MVC page Canvas Tag

Here we will see in detail how to draw our Pie Chart on our MVC Web Application using JQuery.

Inside 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 Chart category colors to array. Here we have fixed to 12 colors and 12 data to add with Pie Chart. If you want you can add more in the code. Here we have 2 set of color combination one with Green base and one with Blue base. User can add as per the requirement here.

  1. var pirChartColor = ["#6CBB3C", "#F87217", "#EAC117", "#EDDA74", "#CD7F32", "#CCFB5D", "#FDD017", "#9DC209", "#E67451", "#728C00","#617C58", "#64E986"]; // green Color Combinations
  2. // var pirChartColor = ["#3090C7", "#BDEDFF", "#78C7C7", "#736AFF", "#7FFFD4", "#3EA99F", "#EBF4FA", "#F9B7FF", "#8BB381", "#BDEDFF", "#B048B5", "#4E387E"]; // Blue Color Combinations
  3. //This method will be used to check for user selected Color Theme and Change the color
  4. function ChangeChartColor() {
  5. if ($('#rdoColorGreen:checked').val() == "Green Theme") {
  6. pirChartColor = ["#6CBB3C", "#F87217", "#EAC117", "#EDDA74", "#CD7F32", "#CCFB5D", "#FDD017", "#9DC209","#E67451", "#728C00", "#617C58", "#64E986"]; // green Color Combinations
  7. lineColor = "#3090C7"; // Blue Color for Line
  8. lineOuterCircleColor = "#6CBB3C"; // Green Color for Outer Circle
  9. }
  10. else {
  11. pirChartColor = ["#3090C7", "#BDEDFF", "#78C7C7", "#736AFF", "#7FFFD4", "#3EA99F", "#EBF4FA", "#F9B7FF","#8BB381", "#BDEDFF", "#B048B5", "#4E387E"]; // Blue Color Combinations
  12. lineColor = "#F87217"; // Orange Color for the Line
  13. lineOuterCircleColor = "#F70D1A "; // Red Color for the outer circle
  14. }
  15. }

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. function drawLengends() {
  3. ctx.fillStyle = "#7F462C";
  4. ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
  5. //Drawing Inner White color Rectange with in Above brown rectangle to plot all the Lables with color,Text and Value.
  6. ctx.fillStyle = "#FFFFFF";
  7. rectInner.startX = rect.startX + 1;
  8. rectInner.startY = rect.startY + 1;
  9. rectInner.w = rect.w - 2;
  10. rectInner.h = rect.h - 2;
  11. ctx.fillRect(rectInner.startX, rectInner.startY, rectInner.w, rectInner.h);
  12. labelBarX = rectInner.startX + 4;
  13. labelBarY = rectInner.startY + 4;
  14. labelBarWidth = rectInner.w - 10;
  15. labelBarHeight = (rectInner.h / noOfPlots) - 5;
  16. colorval = 0;
  17. // here to draw all the rectangle for Lables with Image display
  18. $('#DropDownList1 option').each(function () {
  19. ctx.fillStyle = pirChartColor[colorval];
  20. ctx.fillRect(labelBarX, labelBarY, labelBarWidth, labelBarHeight);
  21. // 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.
  22. if ($('#rdoAlaramOn:checked').val() == "Alert On") {
  23. // Here we can see fo ever chart value we check with the condition .we have initially declare the alertCheckValue as 300.
  24. //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.
  25. //user can change this to your requiremnt if needed.This is optioan function for the Pie Chart.
  26. if (parseInt($(this).val()) >= alertCheckValue) {
  27. ctx.drawImage(greenImage, labelBarX, labelBarY + (labelBarHeight / 3) - 4, imagesize, imagesize);
  28. }
  29. else {
  30. ctx.drawImage(redImage, labelBarX, labelBarY + (labelBarHeight / 3) - 4, imagesize, imagesize);
  31. }
  32. }
  33. //Draw the Pie Chart Label text and Value
  34. ctx.fillStyle = "#000000";
  35. ctx.font = '10pt Calibri';
  36. ctx.fillText($(this).text(), labelBarX + imagesize + 2, labelBarY + (labelBarHeight / 2));
  37. // To Increment and draw the next bar ,label Text and Alart Image.
  38. labelBarY = labelBarY + labelBarHeight + 4;
  39. // labelTextYXVal = labelBarY + labelBarHeight - 4;
  40. colorval = colorval + 1;
  41. });
  42. }
Draw Chart

This is our main function. Here we get all the details to draw our Line Chart. In this function we will draw Chart Titile, Chart Water Mark text, Chart Logo Image and finally call draw Pie chart Method to draw our Pie chart inside Canvas Tag.

  1. // This is the main function to darw the Charts
  2. function drawChart() {
  3. ChangeChartColor();
  4. // asign the images path for both Alert images
  5. greenImage.src = '../images/Green.png';
  6. redImage.src = '../images/Red.png';
  7. LogoImage.src = '../images/shanu.jpg';
  8. // Get the minumum and maximum value.here i have used the hidden filed from code behind wich will stored the Maximum and Minimum value of the Drop down list box.
  9. minDataVal = $('input:text[name=hidListMin]').val();
  10. maxDataVal = $('input:text[name=hidListMax]').val();
  11. // Total no of plots we are going to draw.
  12. noOfPlots = $("#DropDownList1 option").length;
  13. maxValdivValue = Math.round((maxDataVal / noOfPlots));
  14. //storing the Canvas Context to local variable ctx.This variable will be used to draw the Pie Chart
  15. canvas = document.getElementById("canvas");
  16. ctx = canvas.getContext("2d");
  17. //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.
  18. ctx.globalAlpha = 1;
  19. ctx.fillStyle = "#000000";
  20. ctx.strokeStyle = '#000000';
  21. //Every time we clear the canvas and draw the chart
  22. ctx.clearRect(0, 0, canvas.width, canvas.height);
  23. //If need to draw without legend for the PIE Chart
  24. chartWidth = canvas.width - xSpace;
  25. chartHeight = canvas.height - ySpace;
  26. // step 1) Draw legend $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$########################
  27. if ($('#chkLegend:checked').val() == "Show Legend") {
  28. chartWidth = canvas.width - ((canvas.width / 3) - (xSpace / 2));
  29. chartHeight = canvas.height - ySpace - 10;
  30. legendWidth = canvas.width - ((canvas.width / 3) - xSpace);
  31. legendHeight = ySpace;
  32. rect.startX = legendWidth;
  33. rect.startY = legendHeight;
  34. rect.w = canvas.width / 3 - xSpace - 10;
  35. rect.h = canvas.height - ySpace - 10;
  36. //In this method i will draw the legend with the Alert Image.
  37. drawLengends();
  38. }
  39. // end step 1) $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
  40. var chartMidPosition = chartWidth / 2 - 60;
  41. //// //If need to draw with legend
  42. //// chartWidth = canvas.width - ((canvas.width / 3) - (xSpace / 2));
  43. //// chartHeight = canvas.height - ySpace - 10;
  44. // Step 2 ) +++++++++++++ To Add Chart Titel and Company Logo
  45. //To Add Logo to Chart
  46. var logoXVal = canvas.width - LogoImgWidth - 10;
  47. var logolYVal = 0;
  48. //here we draw the Logo for teh chart and i have used the alpha to fade and display the Logo.
  49. ctx.globalAlpha = 0.6;
  50. ctx.drawImage(LogoImage, logoXVal, logolYVal, LogoImgWidth, LogoImgHeight);
  51. ctx.globalAlpha = 1;
  52. ctx.font = '22pt Calibri';
  53. ctx.fillStyle = "#15317E";
  54. var titletxt = $('input:text[name=txtTitle]').val();
  55. ctx.fillText(titletxt, chartMidPosition, chartHeight + 60);
  56. ctx.fillStyle = "#000000";
  57. ctx.font = '10pt Calibri';
  58. // end step 2) +++++++++++ End of Title and Company Logo Add
  59. // Step 3 ) +++++++++++++ toDraw the X-Axis and Y-Axis
  60. // >>>>>>>>> Draw Y-Axis and X-Axis Line(Horizontal Line)
  61. // Draw the axises
  62. //////ctx.beginPath();
  63. //////ctx.moveTo(xSpace, ySpace);
  64. //////// first Draw Y Axis
  65. //////ctx.lineTo(xSpace, chartHeight);
  66. //////// Next draw the X-Axis
  67. //////ctx.lineTo(chartWidth, chartHeight);
  68. //////ctx.stroke();
  69. // >>>>>>>>>>>>> End of X-Axis PIE Draw
  70. //end step 3) +++++++++++++++++++++++
  71. // Step 4) <<<<<<<<<<<<<<<<<<<<<<< To Draw X - Axis Plot Values <<<<<<<<<<<<< }}}}}}
  72. // Draw the X value texts
  73. // --->>>>>>>>>>>> for the Bar Chart i have draw the X-Axis plot in with drawBarChart
  74. // <<<<<<<<<<<<<<<<<<<<<<< End of X Axis Draw
  75. // end Step 4) <<<<<<<<<<<<<<<<<<<<<<<
  76. // Step 5){{{{{{{{{{{{
  77. // {{{{{{{{{{{{{To Draw the Y Axis Plot Values}}}}}}}}}}}}}}
  78. ////////var vAxisPoints = 0;
  79. ////////var max = maxDataVal;
  80. ////////max += 10 - max % 10;
  81. ////////for (var i = 0; i <= maxDataVal; i += maxValdivValue) {
  82. //////// ctx.fillStyle = fotnColor;
  83. //////// ctx.font = axisfontSize + 'pt Calibri';
  84. //////// ctx.fillText(i, xSpace - 40, getYPlotVale(i));
  85. //////// //Here we draw the Y-Axis point PIE
  86. //////// ctx.beginPath();
  87. //////// ctx.moveTo(xSpace, getYPlotVale(i));
  88. //////// ctx.lineTo(xSpace - 10, getYPlotVale(i));
  89. //////// ctx.stroke();
  90. //////// vAxisPoints = vAxisPoints + maxValdivValue;
  91. ////////}
  92. //}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
  93. //Step 5) *********************************************************
  94. //Function to Draw our Chart here we can Call/Bar Chart/PIE Chart or Pie Chart
  95. drawPieChart();
  96. // end step 6) **************
  97. //Step 7) :::::::::::::::::::: to add the Water mark Text
  98. var waterMarktxt = $('input:text[name=txtWatermark]').val();
  99. // Here add the Water mark text at center of the chart
  100. ctx.globalAlpha = 0.1;
  101. ctx.font = '86pt Calibri';
  102. ctx.fillStyle = "#000000";
  103. ctx.fillText(waterMarktxt, chartMidPosition - 40, chartHeight / 2);
  104. ctx.font = '10pt Calibri';
  105. ctx.globalAlpha = 1;
  106. /// end step 7) ::::::::::::::::::::::::::::::::::::::
  107. }
Draw PieChart:

In this function we get all item name and value using foreach of ComboBox and here we plot all value and draw Pie Chart using the ComboBox values. Firstly, we will get total of all values from the getChartTotal() Method. We will be using this total value to calculate and draw our Pie Chart.

  1. function drawPieChart() {
  2. var lastend = 0;
  3. var XvalPosition = xSpace;
  4. chartWidth = (canvas.width / 2) - xSpace;
  5. chartHeight = (canvas.height / 2) - (xSpace / 2);
  6. widthcalculation = parseInt(((parseInt(chartWidth) - 100) / noOfPlots));
  7. //Draw Xaxis Line
  8. //-- draw bar X-Axis and Y-Axis Line
  9. var XLineStartPosition = xSpace;
  10. var yLineStartPosition = xSpace;
  11. var yLineHeight = chartHeight;
  12. var xLineWidth = chartWidth;
  13. colorval = 0;
  14. var chartTotalResult = getChartTotal();
  15. $('#DropDownList1 option').each(function () {
  16. ctx.fillStyle = pirChartColor[colorval];
  17. ctx.beginPath();
  18. ctx.moveTo(chartWidth, chartHeight);
  19. //Here we draw the each Pic Chart arc with values and size.
  20. ctx.arc(chartWidth, chartHeight + 6, chartHeight, lastend, lastend +
  21. (Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult)), false);
  22. ctx.lineTo(chartWidth, chartHeight);
  23. ctx.fill();
  24. lastend += Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult);
  25. //END Draw Bar Graph **************==================********************
  26. colorval = colorval + 1;
  27. });
  28. }
  29. function getChartTotal() {
  30. var chartTotalResult = 0;
  31. $('#DropDownList1 option').each(function () {
  32. chartTotalResult += (typeof parseInt($(this).val()) == 'number') ? parseInt($(this).val()) : 0;
  33. });
  34. return chartTotalResult;
  35. }
Note

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

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