MVC Dynamic Bubble Chart Using Web API, AngularJS And JQuery

chart

Introduction:

In our previous articles we have seen in detail about how to draw Bar, Line, Pie, Bar & Line, and Donut Chart in MVC web Application. In this article we will see how to draw Bubble Chart for MVC applications using HTML5 Canvas, JQuery, WEB API and AngularJS.

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

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 fewer than 12 Items per chart.

  3. Chart Title Text:

    Users 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:

    Users can add their own Company logo to the Chart. (Here for a 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 real time projects. 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 make it 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 numbers of themes as they require.

Blue Theme

Theme

Green Theme

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.   
  3. GO  
  4.   
  5. -- 1) Check for the Database Exists .If the database is exist then drop and create new DB  
  6.   
  7. IFEXISTS(SELECT [name] FROMsys.databasesWHERE [name] ='ItemsDB')  
  8.   
  9. DROPDATABASEItemsDB  
  10.   
  11. GO  
  12.   
  13. CREATEDATABASEItemsDB  
  14.   
  15. GO  
  16.   
  17. USEItemsDB  
  18.   
  19. GO  
  20.   
  21. -- 1) //////////// Item Masters  
  22.   
  23. IFEXISTS(SELECT [name] FROMsys.tablesWHERE [name] ='ItemMaster')  
  24.   
  25. DROPTABLEItemMaster  
  26.   
  27. GO  
  28.   
  29. CREATETABLE [dbo].[ItemMaster](  
  30.   
  31. [ItemID] INTIDENTITYPRIMARYKEY,  
  32.   
  33. [ItemName] [varchar](100)NOTNULL,  
  34.   
  35. [SaleCount] [varchar](10)NOTNULL  
  36.   
  37. )  
  38.   
  39. -- insert sample data to Item Master table  
  40.   
  41. INSERTINTOItemMaster([ItemName],[SaleCount])  
  42.   
  43. VALUES ('Item1','100')  
  44.   
  45. INSERTINTOItemMaster([ItemName],[SaleCount])  
  46.   
  47. VALUES ('Item2','82')  
  48.   
  49. INSERTINTOItemMaster([ItemName],[SaleCount])  
  50.   
  51. VALUES ('Item3','98')  
  52.   
  53. INSERTINTOItemMaster([ItemName],[SaleCount])  
  54.   
  55. VALUES ('Item4','34')  
  56.   
  57. INSERTINTOItemMaster([ItemName],[SaleCount])  
  58.   
  59. VALUES ('Item5','68')  
  60.   
  61. select*fromItemMaster  
  62.   
  63. -- 1)To Select Item Details  
  64.   
  65. -- Author : Shanu  
  66.   
  67. -- Create date : 2016-03-15  
  68.   
  69. -- Description :To Select Item Details  
  70.   
  71. -- Tables used :ItemMaster  
  72.   
  73. -- Modifier : Shanu  
  74.   
  75. -- Modify date : 2016-03-15  
  76.   
  77. -- =============================================  
  78.   
  79. -- To Select Item Details  
  80.   
  81. -- EXEC USP_Item_Select ''  
  82.   
  83. -- =============================================  
  84.   
  85. CREATEPROCEDURE [dbo].[USP_Item_Select]  
  86.   
  87. (  
  88.   
  89. @ItemName VARCHAR(100)=''  
  90.   
  91. )  
  92.   
  93. AS  
  94.   
  95. BEGIN  
  96.   
  97. SELECTItemName,  
  98.   
  99. SaleCount  
  100.   
  101. FROMItemMaster  
  102.   
  103. WHERE  
  104.   
  105. ItemNamelike @ItemName+'%'  
  106.   
  107. OrderBYItemName  
  108.   
  109. END  
  110.   
  111. GO  
  112.   
  113. -- 2) To Insert/Update Item Details  
  114.   
  115. -- Author : Shanu  
  116.   
  117. -- Create date : 2016-03-15  
  118.   
  119. -- Description :To Insert/Update Item Details  
  120.   
  121. -- Tables used :ItemMaster  
  122.   
  123. -- Modifier : Shanu  
  124.   
  125. -- Modify date : 2016-03-15  
  126.   
  127. -- =============================================  
  128.   
  129. -- To Insert/Update Item Details  
  130.   
  131. -- EXEC USP_Item_Edit ''  
  132.   
  133. -- =============================================  
  134.   
  135. CREATEPROCEDURE [dbo].[USP_Item_Edit]  
  136.   
  137. (  
  138.   
  139. @ItemName VARCHAR(100)='',  
  140.   
  141. @SaleCount VARCHAR(10)=''  
  142.   
  143. )  
  144.   
  145. AS  
  146.   
  147. BEGIN  
  148.   
  149. IFNOTEXISTS(SELECT*FROMItemMasterWHEREItemName=@ItemName)  
  150.   
  151. BEGIN  
  152.   
  153. INSERTINTOItemMaster([ItemName],[SaleCount])  
  154.   
  155. VALUES (@ItemName,@SaleCount)  
  156.   
  157.   
  158. Select'Inserted'as results  
  159.   
  160. return;  
  161.   
  162. END  
  163.   
  164. ELSE  
  165.   
  166. BEGIN  
  167.   
  168. UpdateItemMasterSET  
  169.   
  170. SaleCount=@SaleCount  
  171.   
  172. WHEREItemName=@ItemName  
  173.   
  174. Select'Updated'as results  
  175.   
  176. return;  
  177.   
  178. END  
  179.   
  180. Select'Error'as results  
  181.   
  182. END  
  183.   
  184. -- 3)To Max and Min Value  
  185.   
  186. -- Author : Shanu  
  187.   
  188. -- Create date : 2016-03-15  
  189.   
  190. -- Description :To Max and Min Value  
  191.   
  192. -- Tables used :ItemMaster  
  193.   
  194. -- Modifier : Shanu  
  195.   
  196. -- Modify date : 2016-03-15  
  197.   
  198. -- =============================================  
  199.   
  200. -- To Max and Min Value  
  201.   
  202. -- EXEC USP_ItemMaxMin_Select ''  
  203.   
  204. -- =============================================  
  205.   
  206. CREATEPROCEDURE [dbo].[USP_ItemMaxMin_Select]  
  207.   
  208. (  
  209.   
  210. @ItemName VARCHAR(100)=''  
  211.   
  212. )  
  213.   
  214. AS  
  215.   
  216. BEGIN  
  217.   
  218. SELECTMIN(convert(int,SaleCount))asMinValue,  
  219.   
  220. MAX(convert(int,SaleCount))asMaxValue  
  221.   
  222. FROMItemMaster  
  223.   
  224. WHERE  
  225.   
  226. ItemNamelike @ItemName+'%'  
  227.   
  228.   
  229. END  
  230.   
  231. 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.

database

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 is connected we have selected the data base as ItemsDB as we have created the Database using my SQL Script.

Script

Click next and select our tables that 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,

finish

Once Entity has been created in the 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-> 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”.

StudentsController

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)
  • Putis 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 objects 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. {  
  4.   
  5.     ItemsDBEntitiesobjapi = newItemsDBEntities();  
  6.   
  7.     // To get all Item chart detaiuls  
  8.   
  9.     [HttpGet]  
  10.   
  11.     publicIEnumerable < USP_Item_Select_Result > getItemDetails(stringItemName)  
  12.   
  13.     {  
  14.   
  15.         if (ItemName == null)  
  16.   
  17.             ItemName = "";  
  18.   
  19.         returnobjapi.USP_Item_Select(ItemName).AsEnumerable();  
  20.   
  21.     }  
  22.   
  23.     // To get maximum and Minimum value  
  24.   
  25.     [HttpGet]  
  26.   
  27.     publicIEnumerable < USP_ItemMaxMin_Select_Result > getItemMaxMinDetails(stringItemNM)  
  28.   
  29.     {  
  30.   
  31.         if (ItemNM == null)  
  32.   
  33.             ItemNM = "";  
  34.   
  35.         returnobjapi.USP_ItemMaxMin_Select(ItemNM).AsEnumerable();  
  36.   
  37.     }  
  38.   
  39.     // To Insert/Update Item Details  
  40.   
  41.     [HttpGet]  
  42.   
  43.     publicIEnumerable < string > insertItem(stringitemName, stringSaleCount)  
  44.   
  45.     {  
  46.   
  47.         returnobjapi.USP_Item_Edit(itemName, SaleCount).AsEnumerable();  
  48.   
  49.     }  
  50.   
  51. }  

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”

Controller

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.   
  3. /// <reference path="../angular.min.js" />  
  4.   
  5. /// <reference path="../angular-animate.js" />  
  6.   
  7. /// <reference path="../angular-animate.min.js" />  
  8.   
  9. var app;  
  10.   
  11. (function () {  
  12.   
  13. app = angular.module("AngularJs_Module", ['ngAnimate']);  
  14.   
  15. })();  

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.       {  
  3.   
  4.             $scope.date = newDate();  
  5.   
  6.             // <reference path="../angular.js" />  
  7.   
  8.             /// <reference path="../angular.min.js" />  
  9.   
  10.             /// <reference path="../angular-animate.js" />  
  11.   
  12.             /// <reference path="../angular-animate.min.js" />  
  13.   
  14.             var app;  
  15.   
  16.             (function() {  
  17.   
  18.                 app = angular.module("RESTClientModule", ['ngAnimate']);  
  19.   
  20.             })();  
  21.   
  22.             app.controller("AngularJs_Controller", function($scope, $timeout, $rootScope, $window, $http)  
  23.                {  
  24.   
  25.                         $scope.date = newDate();  
  26.   
  27.                         $scope.MyName = "shanu";  
  28.   
  29.                         $scope.sItemName = "";  
  30.   
  31.                         $scope.itemCount = 5;  
  32.   
  33.                         $scope.selectedItem = "";  
  34.   
  35.                         $scope.chartTitle = "SHANU Bubble Chart";  
  36.   
  37.                         $scope.waterMark = "SHANU";  
  38.   
  39.                         $scope.ItemValues = 0;  
  40.   
  41.                         $scope.ItemNames = "";  
  42.   
  43.                         $scope.showItemAdd = false;  
  44.   
  45.                         $scope.minsnew = 0;  
  46.   
  47.                         $scope.maxnew = 0;  

2. Methods

Select Method

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.   
  4. // This method is to get all the Item Details to bind in Combobox for plotting in Graph  
  5.   
  6. functionselectuerRoleDetails(ItemName)  
  7. {  
  8.   
  9.     $http.get('/api/ItemAPI/getItemDetails/',  
  10.      {  
  11.         params:  
  12.         {  
  13.             ItemName: ItemName  
  14.         }  
  15.     }).success(function(data) {  
  16.   
  17.         $scope.itemData = data;  
  18.   
  19.         $scope.itemCount = $scope.itemData.length;  
  20.   
  21.         $scope.selectedItem = $scope.itemData[0].SaleCount;  
  22.   
  23.     })  
  24.   
  25.     .error(function() {  
  26.   
  27.         $scope.error = "An Error has occured while loading posts!";  
  28.   
  29.     });  
  30.   
  31.     $http.get('/api/ItemAPI/getItemMaxMinDetails/', {  
  32.         params: {  
  33.             ItemNM: $scope.sItemName  
  34.         }  
  35.     }).success(function(data) {  
  36.   
  37.         $scope.itemDataMaxMin = data;  
  38.   
  39.         $scope.minsnew = $scope.itemDataMaxMin[0].MinValue;  
  40.   
  41.         $scope.maxnew = $scope.itemDataMaxMin[0].MaxValue;  
  42.   
  43.     })  
  44.   
  45.     .error(function() {  
  46.   
  47.         $scope.error = "An Error has occured while loading posts!";  
  48.   
  49.     });  
  50.   
  51. }  

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 Method

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

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

Here we will see in detail about how to draw our Bubble 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 datas to add with Bubble Chart. If you want you can add more from here. Here we have 2 sets of color combination one with Green base and one with a 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.   
  3. // varpirChartColor = ["#3090C7", "#BDEDFF", "#78C7C7", "#736AFF", "#7FFFD4", "#3EA99F", "#EBF4FA", "#F9B7FF", "#8BB381", "#BDEDFF", "#B048B5", "#4E387E"]; // Blue Color Combinations  
  4.   
  5.   
  6. //This method will be used to check for user selected Color Theme and Change the color  
  7.   
  8. functionChangeChartColor()  
  9. {  
  10.   
  11.     if ($('#rdoColorGreen:checked').val() == "Green Theme") {  
  12.   
  13.         pirChartColor = ["#6CBB3C""#F87217""#EAC117""#EDDA74""#CD7F32""#CCFB5D""#FDD017""#9DC209""#E67451""#728C00""#617C58""#64E986"]; // green Color Combinations  
  14.   
  15.         lineColor = "#3090C7"// Blue Color for Line  
  16.   
  17.         lineOuterCircleColor = "#6CBB3C"// Green Color for Outer Circle  
  18.   
  19.     } else {  
  20.   
  21.         pirChartColor = ["#3090C7""#BDEDFF""#78C7C7""#736AFF""#7FFFD4""#3EA99F""#EBF4FA""#F9B7FF""#8BB381""#BDEDFF""#B048B5""#4E387E"]; // Blue Color Combinations  
  22.   
  23.         lineColor = "#F87217"// Orange Color for the Line  
  24.   
  25.         lineOuterCircleColor = "#F70D1A "// Red Color for the outer circle  
  26.   
  27.     }  
  28.   
  29. }  

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.   
  9. // Return the y value  
  10.   
  11. functiongetYPlotVale(val) {  
  12.   
  13.     returnchartHeight - (((chartHeight - xSpace) / maxDataVal) * val);  
  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. functiondrawLengends()  
  3. {  
  4.   
  5.     ctx.fillStyle = "#7F462C";  
  6.   
  7.     ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);  
  8.   
  9.     //Drawing Inner White color Rectange with in Above brown rectangle to plot all the Lables with color,Text and Value.  
  10.   
  11.     ctx.fillStyle = "#FFFFFF";  
  12.   
  13.     rectInner.startX = rect.startX + 1;  
  14.   
  15.     rectInner.startY = rect.startY + 1;  
  16.   
  17.     rectInner.w = rect.w - 2;  
  18.   
  19.     rectInner.h = rect.h - 2;  
  20.   
  21.     ctx.fillRect(rectInner.startX, rectInner.startY, rectInner.w, rectInner.h);  
  22.   
  23.     labelBarX = rectInner.startX + 4;  
  24.   
  25.     labelBarY = rectInner.startY + 4;  
  26.   
  27.     labelBarWidth = rectInner.w - 10;  
  28.   
  29.     labelBarHeight = (rectInner.h / noOfPlots) - 5;  
  30.   
  31.     colorval = 0;  
  32.   
  33.     // here to draw all the rectangle for Lables with Image display  
  34.   
  35.     $('#DropDownList1 option').each(function()  
  36.        {  
  37.   
  38.         ctx.fillStyle = pirChartColor[colorval];  
  39.   
  40.         ctx.fillRect(labelBarX, labelBarY, labelBarWidth, labelBarHeight);  
  41.   
  42.         // 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.  
  43.   
  44.         if ($('#rdoAlaramOn:checked').val() == "Alert On") {  
  45.   
  46.             // Here we can see fo ever chart value we check with the condition .we have initially declare the alertCheckValue as 300.  
  47.   
  48.             //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.  
  49.   
  50.             //user can change this to your requiremnt if needed.This is optioan function for the Pie Chart.  
  51.   
  52.             if (parseInt($(this).val()) >= alertCheckValue) {  
  53.   
  54.                 ctx.drawImage(greenImage, labelBarX, labelBarY + (labelBarHeight / 3) - 4, imagesize, imagesize);  
  55.   
  56.             } else {  
  57.   
  58.                 ctx.drawImage(redImage, labelBarX, labelBarY + (labelBarHeight / 3) - 4, imagesize, imagesize);  
  59.   
  60.             }  
  61.   
  62.         }  
  63.   
  64.         //Draw the Bubble Chart Label text and Value  
  65.   
  66.         ctx.fillStyle = "#000000";  
  67.   
  68.         ctx.font = '10pt Calibri';  
  69.   
  70.         ctx.fillText($(this).text(), labelBarX + imagesize + 2, labelBarY + (labelBarHeight / 2));  
  71.   
  72.         // To Increment and draw the next bar ,label Text and Alart Image.  
  73.   
  74.         labelBarY = labelBarY + labelBarHeight + 4;  
  75.   
  76.         // labelTextYXVal = labelBarY + labelBarHeight - 4;  
  77.   
  78.         colorval = colorval + 1;  
  79.   
  80.     });  
  81.   
  82. }  

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

  1. // This is the main function to darw the Charts  
  2. function drawChart() {  
  3.   
  4.     ChangeChartColor();  
  5.   
  6.     // asign the images path for both Alert images  
  7.   
  8.     greenImage.src = '../images/Green.png';  
  9.   
  10.     redImage.src = '../images/Red.png';  
  11.   
  12.     LogoImage.src = '../images/shanu.jpg';  
  13.   
  14.     // 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.  
  15.   
  16.     minDataVal = $('input:text[name=hidListMin]').val();  
  17.   
  18.     maxDataVal = $('input:text[name=hidListMax]').val();  
  19.   
  20.     // Total no of plots we are going to draw.  
  21.   
  22.     noOfPlots = $("#DropDownList1 option").length;  
  23.   
  24.     maxValdivValue = Math.round((maxDataVal / noOfPlots));  
  25.   
  26.     //storing the Canvas Context to local variable ctx.This variable will be used to draw the Pie Chart  
  27.   
  28.     canvas = document.getElementById("canvas");  
  29.   
  30.     ctx = canvas.getContext("2d");  
  31.   
  32.     //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.  
  33.   
  34.     ctx.globalAlpha = 1;  
  35.   
  36.     ctx.fillStyle = "#000000";  
  37.   
  38.     ctx.strokeStyle = '#000000';  
  39.   
  40.     //Every time we clear the canvas and draw the chart  
  41.   
  42.     ctx.clearRect(0, 0, canvas.width, canvas.height);  
  43.   
  44.     //If need to draw with out legend for the PIE Chart  
  45.   
  46.     chartWidth = canvas.width - xSpace;  
  47.   
  48.     chartHeight = canvas.height - ySpace;  
  49.   
  50.     // step 1) Draw legend $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$########################  
  51.   
  52.     if ($('#chkLegend:checked').val() == "Show Legend") {  
  53.   
  54.         chartWidth = canvas.width - ((canvas.width / 3) - (xSpace / 2));  
  55.   
  56.         chartHeight = canvas.height - ySpace - 10;  
  57.   
  58.         legendWidth = canvas.width - ((canvas.width / 3) - xSpace);  
  59.   
  60.         legendHeight = ySpace;  
  61.   
  62.         rect.startX = legendWidth;  
  63.   
  64.         rect.startY = legendHeight;  
  65.   
  66.         rect.w = canvas.width / 3 - xSpace - 10;  
  67.   
  68.         rect.h = canvas.height - ySpace - 10;  
  69.   
  70.         //In this method i will draw the legend with the Alert Image.  
  71.   
  72.         drawLengends();  
  73.   
  74.     }  
  75.   
  76.     // end step 1) $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$  
  77.   
  78.     varchartMidPosition = chartWidth / 2 - 60;  
  79.   
  80.     //// //If need to draw with legend  
  81.   
  82.     //// chartWidth = canvas.width - ((canvas.width / 3) - (xSpace / 2));  
  83.   
  84.     //// chartHeight = canvas.height - ySpace - 10;  
  85.   
  86.     // Step 2 ) +++++++++++++ To Add Chart Titel and Company Logo  
  87.   
  88.     //To Add Logo to Chart  
  89.   
  90.     varlogoXVal = canvas.width - LogoImgWidth - 10;  
  91.   
  92.     varlogolYVal = 0;  
  93.   
  94.     //here we draw the Logo for teh chart and i have used the alpha to fade and display the Logo.  
  95.   
  96.     ctx.globalAlpha = 0.6;  
  97.   
  98.     ctx.drawImage(LogoImage, logoXVal, logolYVal, LogoImgWidth, LogoImgHeight);  
  99.   
  100.     ctx.globalAlpha = 1;  
  101.   
  102.     ctx.font = '22pt Calibri';  
  103.   
  104.     ctx.fillStyle = "#15317E";  
  105.   
  106.     vartitletxt = $('input:text[name=txtTitle]').val();  
  107.   
  108.     ctx.fillText(titletxt, chartMidPosition, chartHeight + 60);  
  109.   
  110.     ctx.fillStyle = "#000000";  
  111.   
  112.     ctx.font = '10pt Calibri';  
  113.   
  114.     // end step 2) +++++++++++ End of Title and Company Logo Add  
  115.   
  116.     // Step 3 ) +++++++++++++ toDraw the X-Axis and Y-Axis  
  117.   
  118.     // >>>>>>>>> Draw Y-Axis and X-Axis Line(Horizontal Line)  
  119.   
  120.     // Draw the axises  
  121.   
  122.     //////ctx.beginPath();  
  123.   
  124.     //////ctx.moveTo(xSpace, ySpace);  
  125.   
  126.     //////// first Draw Y Axis  
  127.   
  128.     //////ctx.lineTo(xSpace, chartHeight);  
  129.   
  130.     //////// Next draw the X-Axis  
  131.   
  132.     //////ctx.lineTo(chartWidth, chartHeight);  
  133.   
  134.     //////ctx.stroke();  
  135.   
  136.     // >>>>>>>>>>>>> End of X-Axis PIE Draw  
  137.   
  138.     //end step 3) +++++++++++++++++++++++  
  139.   
  140.     // Step 4) <<<<<<<<<<<<<<<<<<<<<<< To Draw X - Axis Plot Values <<<<<<<<<<<<< }}}}}}  
  141.   
  142.     // Draw the X value texts  
  143.   
  144.     // --->>>>>>>>>>>> for the Bar Chart i have draw the X-Axis plot in with drawBarChart  
  145.   
  146.     // <<<<<<<<<<<<<<<<<<<<<<< End of X Axis Draw  
  147.   
  148.     // end Step 4) <<<<<<<<<<<<<<<<<<<<<<<  
  149.   
  150.     // Step 5){{{{{{{{{{{{  
  151.   
  152.     // {{{{{{{{{{{{{To Draw the Y Axis Plot Values}}}}}}}}}}}}}}  
  153.   
  154.     ////////varvAxisPoints = 0;  
  155.   
  156.     ////////var max = maxDataVal;  
  157.   
  158.     ////////max += 10 - max % 10;  
  159.   
  160.     ////////for (vari = 0; i<= maxDataVal; i += maxValdivValue) {  
  161.   
  162.     //////// ctx.fillStyle = fotnColor;  
  163.   
  164.     //////// ctx.font = axisfontSize + 'pt Calibri';  
  165.   
  166.     //////// ctx.fillText(i, xSpace - 40, getYPlotVale(i));  
  167.   
  168.     //////// //Here we draw the Y-Axis point PIE  
  169.   
  170.     //////// ctx.beginPath();  
  171.   
  172.     //////// ctx.moveTo(xSpace, getYPlotVale(i));  
  173.   
  174.     //////// ctx.lineTo(xSpace - 10, getYPlotVale(i));  
  175.   
  176.     //////// ctx.stroke();  
  177.   
  178.     //////// vAxisPoints = vAxisPoints + maxValdivValue;  
  179.   
  180.     ////////}  
  181.   
  182.     //}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}  
  183.   
  184.     //Step 5) *********************************************************  
  185.   
  186.     //Function to Draw our Chart here we can Call/Bar Chart/PIE Chart or Pie Chart  
  187.   
  188.     drawBubbleChart();  
  189.   
  190.     // end step 6) **************  
  191.   
  192.     //Step 7) :::::::::::::::::::: to add the Water mark Text  
  193.   
  194.     varwaterMarktxt = $('input:text[name=txtWatermark]').val();  
  195.   
  196.     // Here add the Water mark text at center of the chart  
  197.   
  198.     ctx.globalAlpha = 0.1;  
  199.   
  200.     ctx.font = '86pt Calibri';  
  201.   
  202.     ctx.fillStyle = "#000000";  
  203.   
  204.     ctx.fillText(waterMarktxt, chartMidPosition - 40, chartHeight / 2);  
  205.   
  206.     ctx.font = '10pt Calibri';  
  207.   
  208.     ctx.globalAlpha = 1;  
  209.   
  210.     /// end step 7) ::::::::::::::::::::::::::::::::::::::  
  211.   
  212. }  

DrawBubbleChart:

In this function we get all item names and value using foreachof ComboBox and here we plot all values and draw Bubble chart using the ComboBoxvalues. Using the value we will draw our Bubble chart on canvas tag from this method.

  1. functiondrawBubbleChart()  
  2. {  
  3.   
  4.     // *************** To Draw the Line Dot Cericle  
  5.   
  6.     ctx.globalAlpha = 0.8;  
  7.   
  8.     //For Outer Blue Dot  
  9.   
  10.     varbubbleSize = 40;  
  11.   
  12.     ival = 0;  
  13.   
  14.     $('#DropDownList1 option').each(function()  
  15.     {  
  16.   
  17.         ctx.fillStyle = pirChartColor[ival];  
  18.   
  19.         ctx.strokeStyle = pirChartColor[ival];  
  20.   
  21.         ctx.beginPath();  
  22.   
  23.         ctx.arc(getXPlotvalue(ival), getYPlotVale($(this).val()), bubbleSize, bubbleSize, Math.PI * 2, true);  
  24.   
  25.         ctx.fill();  
  26.   
  27.         ival = ival + 1;  
  28.   
  29.     });  
  30.   
  31.     ctx.lineWidth = 1;  
  32.   
  33. }  

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,Donut and Bubble Chart.

chart

Tested Browsers:

  • Chrome
  • Firefox
  • IE10

Read more articles on ASP.NET:


Similar Articles