Draw ASP.Net Chart Using HTML5 and jQuery



In my previous article Draw ASP.NET Bar Chart Using HTML5 and jQuery I explained how to create a simple Web Bar Chart using HTML5 and jQuery. This article shows how to draw our own Chart's like.

  1. Line Chart
  2. Bar Chart
  3. Line & Bar Chart
  4. Pie Chart
  5. Donut Chart
  6. Bubble Chart
In the Source Code Zip file you can find both Visual Studio 2010 and Visual Studio 2013 solutions. You can use any solutions depending on your Visual Studio Versions. 

My Bar Chart Features

All this following features will be used for all chart types we can see one by one in code part.


Chart Source Data

The plot data from a database / Data Table / List / XML file or any source depending on your requirements. The only thing you need to do is get the data from your source and bind the result to a Dropdown List. (With the value and text. Here the value will be an integer for plotting the value and the text will be to be displayed in the label.)

Chart Number of Category

Here I have limited the Chart Category display from a minimum of 1 to a maximum of 12. This means here dynamically we can load the plots category depending on the data source. But limited, since the display plots value is within 12 plots. (But the user can redesign the code easily depending on requirements.)

Chart Title Text

The user can add their own Chart Title and dynamically change the titles if required. Here in my example I will draw the Title TextBox text at the bottom of the Bar Chart. (The user can redesign and customize this depending on requirements.)

Chart Water Mark Text

In some cases we need to add our company name as a Watermark to our Bar Chart. Here in my example I will draw the Water Mark TextBox text at the center of the Bar Chart. (The user can redesign and customize this depending on requirements.)

Chart Company LOGO

The user can add their own company logo to the Chart. (Here for the sample I have added my own image as a log at the top-right corner. (The user can redesign and customize this depending on your requirements if needed.)

Chart Alert Image

Chart Alert Image Display: You can see from the article the first Image has Labels, I have displayed the Bar Chart label Text and Alert Image. If the “Alert On” radio button is checked I will display the Alert Image. If the “Alert Off” radio button is clicked then the Alert Image will not be displayed.

The use of an Alert Image

Let's consider a real project. For example we need to display a Pie Chart for a manufacturing factory with production results Good and Bad. For example if the production result for each quality value is above 300 then we need to display the Alert Green image and if the quality value is below 300 then we need to display the Red image with label bars.

This Alert Image will be easy to identify each quality result as good or bad. (Here for a sample I have used 2 quality check and displayed using Green and Red images but users can customize depending on requirements and add your own image and logic.)

Chart Color Theme

The user can select any one Color Theme for the Chart as Green Theme or Blue Theme.

Legend Display

The user can enable or disable the display of the Legend for the Chart using the check box. If the “Show Legend“ Checkbox is checked then the chart will be displayed with a label and alert image. If not checked then the legend will not be displayed in the chart.

Save Chart as Image

The user can save the chart as an image. Here we can see a Bar Chart with another theme with a Blue base but without displaying the Alert Image.

Code part

Step 1: Create new ASP.NET Web project

Click Start then All Programs then open Visual Studio 2013 or Visual Studio 2010 (depending on your installed version), select either one. Click "File" -> "New" -> "Project..." then select ASP.NET WEB Project then click Create.

Step 2:Add canvas tag to your webform

Add a new Webform and add a Canvas ELEMENT within the Section Tag.
  1. <SECTION style="border-style: solid; border-width: 2px; width: 800px;">  
  2. <CANVAS HEIGHT="600px" WIDTH="800px" ID="canvas">  
  3. Your browser is not supporting HTML5 Canvas .Upgrade Browser to view this program or check with Chrome or in Firefox.  
  4. </CANVAS>  
  5. </SECTION>  
Step 3: Script to Draw Chart in step-by-step

Script Global variable

First add the global variable that needs to be used to draw a chart inside the script tag.

I have commented the line before for each variable about its use. Here the ChartWidth and chartHeigth variables will be used to store and draw the Chart width and height depending on the Canvas size.
  1. //public Canvas object to use in all the functions.  
  2. //this variable will be used to check for the result of Alert Image display  
  3. var alertCheckValue = 300;  
  4.   
  5. //Adding the Pic Chart Colors to array .Here i have fixed to 12 colors and 12 datas to add as Pic Chart.if you want you can add more from here.  
  6. var pirChartColor = ["#6CBB3C""#F87217""#EAC117""#EDDA74""#CD7F32""#CCFB5D""#FDD017""#9DC209""#E67451""#728C00""#617C58""#64E986"]; // green Color Combinations  
  7. // var pirChartColor = ["#3090C7", "#BDEDFF", "#78C7C7", "#736AFF", "#7FFFD4", "#3EA99F", "#EBF4FA", "#F9B7FF", "#8BB381", "#BDEDFF", "#B048B5", "#4E387E"]; // Blue Color Combinations  
  8. var lineColor = "#3090C7";  
  9. var lineOuterCircleColor = "#6CBB3C";  
  10. var lineInnerCircleColor = "#FFFFFF";  
  11.   
  12. //declare the Canvas object  
  13. var canvas;  
  14. var chartCTX;  
  15.   
  16. // declare the Border Space,Chart Start X and Y Position;  
  17. var xSpace = 80;  
  18. var ySpace = 80;  
  19. //declare the Chart DrawWidth and Hegith  
  20. var chartWidth, chartHeight;  
  21.   
  22. // declared the Chart Legend Width and Hegit  
  23. var legendWidth, legendHeight;  
  24.   
  25. //declared the Chart data Minimum Value,maximum Value and Noofplots(Bars/Arc and Line points)  
  26. var minDataVal, maxDataVal, noOfPlots;  
  27.   
  28. //here we declare the Image for the Chart legend alert status display.  
  29. var greenImage = new Image();  
  30. var redImage = new Image();  
  31. //Alert Image Size widht and hegith  
  32. var imagesize = 20;  
  33. var maxValdivValue;  
  34. //Here we declare the X,YAxis Font size and Color  
  35. var fotnColor = "#000000";  
  36. var axisfontSize = 10;  
  37.   
  38. var LogoImage = new Image();  
  39. var LogoImgWidth = 120;  
  40. var LogoImgHeight = 70;  
  41. // This arrawy wil be used to draw the Legends   
  42. rect = {};  
  43. rectInner = {};  
Note: I have used the Master pages so in the script before each control I will use the ContentPlaceHolderID.

For example my Green color theme radio button id is rdoColorGreen. But for jQuery I will be use like this cphBody_rdoColorGreen. For example if we use a master page then we add a ContentPlaceHolderID like this in the script:
  1. if ($('#cphBody_rdoColorGreen:checked').val() == "rdoColorGreen")  
  2. {  
  3. }  
If we do not use the master page and we draw a chat in our webform without including the master page then we need to remove the contentploceholder id like this.
  1. if ($('# rdoColorGreen:checked').val() == "rdoColorGreen")   
  2. {  
  3. }“  
2. Chart Color Theme

This method depends on the user color selection checked from the radio button. I will select the Color Array to fill in the color for each plots. This is a common function that can be used to draw any chart like Line, Bar, Pie, Donut and and so on.
  1. function ChangeChartColor()   
  2. {  
  3.    if ($('#cphBody_rdoColorGreen:checked').val() == "rdoColorGreen"
  4.    {  
  5.          pirChartColor = ["#6CBB3C""#F87217""#EAC117""#EDDA74""#CD7F32""#CCFB5D""#FDD017""#9DC209""#E67451""#728C00""#617C58""#64E986"]; // green Color Combinations  
  6.          lineColor = "#3090C7"// Blue Color for Line  
  7.          lineOuterCircleColor = "#6CBB3C"// Green Color for Outer Circle  
  8.    }  
  9.    else 
  10.    {  
  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. }  
3. Chart Color Theme

This method will be used to get the X and Y point to draw our chart. This is a common function that can be used to draw any chart like Line, Bar, Pie, Donut and so on.
  1. function getXPlotvalue(val)   
  2. {  
  3.     return (Math.round((chartWidth - xSpace) / noOfPlots)) * val + (xSpace * 1.5)-24;  
  4. }  
  5.   
  6. // Return the y pixel for a graph point  
  7. function getYPlotVale(val) 
  8. {  
  9.     return chartHeight - (((chartHeight - xSpace) / maxDataVal) * val);  
  10. }  
4.Draw legend

This method will be used to draw the legend for the chart. In this method I will draw a label with color and add label text and an Alert Image inside the label. This is a common function that can be used to draw any chart like Line, Bar, Pie, Donut and and so on. (In the Line chart I don't use this Legend since a line chart is not required for the Label display.)
  1. // This function is used to draw the Legend  
  2. function drawLengends() 
  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.     labelBarX = rectInner.startX + 4;  
  14.     labelBarY = rectInner.startY + 4;  
  15.     labelBarWidth = rectInner.w - 10;  
  16.     labelBarHeight = (rectInner.h / noOfPlots) - 5;  
  17.     colorval = 0;  
  18.     // here to draw all the rectangle for Lables with Image display  
  19.     $('#cphBody_DropDownList1 option').each(function () 
  20.     {  
  21.         ctx.fillStyle = pirChartColor[colorval];  
  22.         ctx.fillRect(labelBarX, labelBarY, labelBarWidth, labelBarHeight);  
  23.      // 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.  
  24.         if ($('#cphBody_rdoAlaramOn:checked').val() == "rdoAlaramOn"
  25.         {  
  26.            // Here we can see fo ever chart value we check with the condition .we have initially declare the alertCheckValue as 300.  
  27.            //so if the Chart Plot value is Greater then or equal to the check value 
  28.            then we display the Green Image else we display the Red Image.  
  29.            //user can change this to your requiremnt if needed.This is optioan function for the Pie Chart.  
  30.            if (parseInt($(this).val()) >= alertCheckValue) 
  31.            {  
  32.                ctx.drawImage(greenImage, labelBarX, labelBarY + (labelBarHeight / 3) - 4, imagesize, imagesize);  
  33.            }  
  34.            else 
  35.            {  
  36.                ctx.drawImage(redImage, labelBarX, labelBarY + (labelBarHeight / 3) - 4, imagesize, imagesize);  
  37.            }  
  38.         }  
  39.         //Draw the Pie Chart Label text and Value  
  40.         ctx.fillStyle = "#000000";  
  41.         ctx.font = '10pt Calibri';  
  42.         ctx.fillText($(this).text(), labelBarX + imagesize + 2, labelBarY + (labelBarHeight / 2));  
  43.   
  44.         // To Increment and draw the next bar ,label Text and Alart Image.  
  45.         labelBarY = labelBarY + labelBarHeight + 4;  
  46.         //  labelTextYXVal = labelBarY + labelBarHeight - 4;  
  47.   
  48.         colorval = colorval + 1;  
  49.     });  
  50. }  
5. Draw Chart

This is the main method. the In button Draw Chart Image button clicks I will call this method first. From this method I will call other methods depending on requirements.
In this method I have explained in comments before each line of code. This method has 5 main code parts as we can see here. In the comments I have explained using steps at each part.  
  1. First we calculate and store all the necessary variables like Item Maximum Value, Item total Count, Chart Width, Chart Height, legend Width, Legend height at and so on.
  2. Draw legend.
  3. Add Chart Title and Logo to chart.
  4. Draw X-Axis Line with Plot text.
  5. Draw Y- Axis Line with Y-Axis plot value.
  6. Draw Bar Chart method (Next we call the method to draw our chart. For each chart I have created a separate method. For example to draw the Bar Chart I will call the “drawBarChart()” method, to draw a line chart I will call the “drawLineChart()” method and so on.
  7. Draw the Watermark text for the chart.  
  1. // This is the main function to darw the Charts  
  2. function drawChart() 
  3. {  
  4.     ChangeChartColor();  
  5.     // asign the images path for both Alert images  
  6.     greenImage.src = '../images/Green.png';  
  7.     redImage.src = '../images/Red.png';  
  8.     LogoImage.src = '../images/shanu.jpg';  
  9.     // Get the minumum and maximum value.here i have used the hidden filed from code behind wich will 
  10.         stored the Maximum and Minimum value of the Drop down list box.  
  11.     minDataVal = $('#cphBody_hidListMin').val();  
  12.     maxDataVal = $('#cphBody_hidListMax').val();  
  13.     // Total no of plots we are going to draw.  
  14.     noOfPlots = $("#cphBody_DropDownList1 option").length;  
  15.     maxValdivValue = Math.round((maxDataVal / noOfPlots));  
  16.     //storing the Canvas Context to local variable ctx.This variable will be used to draw the Pie Chart  
  17.     canvas = document.getElementById("canvas");  
  18.     ctx = canvas.getContext("2d");  
  19.     //globalAlpha - > is used to display the 100% opoacity of chart .because at the bottom of 
  20.          the code I have used the opacity to 0.1 to display the water mark text with fade effect.  
  21.     ctx.globalAlpha = 1;  
  22.     ctx.fillStyle = "#000000";  
  23.     ctx.strokeStyle = '#000000';  
  24.     //Every time we clear the canvas and draw the chart   
  25.     ctx.clearRect(0, 0, canvas.width, canvas.height);  
  26.   
  27.     //If need to draw with out legend for the Line Chart  
  28.     chartWidth = canvas.width - xSpace;  
  29.     chartHeight = canvas.height - ySpace;  
  30.     //  step 1) Draw legend $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$########################  
  31.     if ($('#cphBody_chkLegend:checked').val() == "on"
  32.     {  
  33.          chartWidth = canvas.width - ((canvas.width / 3) - (xSpace / 2));  
  34.          chartHeight = canvas.height - ySpace - 10;  
  35.   
  36.          legendWidth = canvas.width - ((canvas.width / 3) - xSpace);  
  37.          legendHeight = ySpace;  
  38.   
  39.          rect.startX = legendWidth;  
  40.          rect.startY = legendHeight;  
  41.          rect.w = canvas.width / 3 - xSpace - 10;  
  42.          rect.h = canvas.height - ySpace - 10;  
  43.          //In this method i will draw the legend with the Alert Image.  
  44.          drawLengends();  
  45.      }  
  46.      // end step 1) $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$  
  47.      var chartMidPosition = chartWidth / 2 - 60;  
  48.   
  49.       ////        //If need to draw with legend  
  50.       ////        chartWidth = canvas.width - ((canvas.width / 3) - (xSpace / 2));  
  51.       ////        chartHeight = canvas.height - ySpace - 10;  
  52.   
  53.       // Step 2 ) +++++++++++++ To Add Chart Titel and  Company Logo  
  54.       //To Add Logo to Chart  
  55.   
  56.       var logoXVal = canvas.width - LogoImgWidth - 10;  
  57.       var logolYVal = 0;  
  58.   
  59.       //here we draw the Logo for teh chart and i have used the alpha to fade and display the Logo.  
  60.       ctx.globalAlpha = 0.6;  
  61.   
  62.       ctx.drawImage(LogoImage, logoXVal, logolYVal, LogoImgWidth, LogoImgHeight);  
  63.   
  64.       ctx.globalAlpha = 1;  
  65.   
  66.       ctx.font = '22pt Calibri';  
  67.       ctx.fillStyle = "#15317E";  
  68.       ctx.fillText($('#cphBody_txtTitle').val(), chartMidPosition, chartHeight + 60);  
  69.   
  70.   
  71.       ctx.fillStyle = "#000000";  
  72.       ctx.font = '10pt Calibri';  
  73.   
  74.       // end step 2) +++++++++++ End of Title and Company Logo Add  
  75.   
  76.       // Step 3 ) +++++++++++++ toDraw the X-Axis and Y-Axis  
  77.    
  78.       //  >>>>>>>>> Draw Y-Axis and X-Axis Line(Horizontal Line)  
  79.       // Draw the axises  
  80.      ctx.beginPath();  
  81.      ctx.moveTo(xSpace, ySpace);  
  82.      // first Draw Y Axis  
  83.      ctx.lineTo(xSpace, chartHeight);  
  84.   
  85.      // Next draw the X-Axis  
  86.      ctx.lineTo(chartWidth, chartHeight);  
  87.      ctx.stroke();  
  88.      //  >>>>>>>>>>>>> End of X-Axis Line Draw  
  89.      //end step 3) +++++++++++++++++++++++  
  90.   
  91.   
  92.      // Step 4) <<<<<<<<<<<<<<<<<<<<<<< To Draw X - Axis Plot Values <<<<<<<<<<<<< }}}}}}  
  93.      // Draw the X value texts  
  94.      // --->>>>>>>>>>>>  for the Bar Chart i have draw the X-Axis plot in  drawBarChart  
  95.      //  <<<<<<<<<<<<<<<<<<<<<<< End of X Axis Draw  
  96.   
  97.      // end Step 4) <<<<<<<<<<<<<<<<<<<<<<<  
  98.   
  99.      // Step 5){{{{{{{{{{{{  
  100.      // {{{{{{{{{{{{{To Draw the Y Axis Plot Values}}}}}}}}}}}}}}  
  101.      var vAxisPoints = 0;  
  102.      var max = maxDataVal;  
  103.      max += 10 - max % 10;  
  104.      for (var i = 0; i <= maxDataVal; i += maxValdivValue) 
  105.     {  
  106.    
  107.        ctx.fillStyle = fotnColor;  
  108.        ctx.font = axisfontSize + 'pt Calibri';          
  109.        ctx.fillText(i, xSpace - 40, getYPlotVale(i));  
  110.   
  111.        //Here we draw the Y-Axis point line  
  112.        ctx.beginPath();  
  113.        ctx.moveTo(xSpace, getYPlotVale(i));  
  114.   
  115.        ctx.lineTo(xSpace - 10, getYPlotVale(i));  
  116.        ctx.stroke();  
  117.        vAxisPoints = vAxisPoints + maxValdivValue;  
  118.    
  119.     }  
  120.   
  121.    //{{{{{{{{{{{{{{ End of Y- Axis Plot Values  
  122.   
  123.    //end  Step 5) {{{{{{{{{{{{{{{{{{  
  124.   
  125.   
  126.    //Step 5) *********************************************************  
  127.    //Function to Draw our Chart here we can Call/Bar Chart/Line Chart or Pie Chart  
  128.   
  129.    // to Draw Bar Chart  
  130.    drawBarChart();  
  131.  
  132.    // to Draw line Chart  
  133.    drawLineChart();  
  134.    // end step 6) **************  
  135.   
  136.    //Step 7)  :::::::::::::::::::: to add the Water mark Text  
  137.   
  138.    // Here add the Water mark text at center of the chart  
  139.    ctx.globalAlpha = 0.1;  
  140.    ctx.font = '86pt Calibri';     
  141.    ctx.fillStyle = "#000000";  
  142.    ctx.fillText($('#cphBody_txtWatermark').val(), chartMidPosition - 40, chartHeight / 2);  
  143.   
  144.    ctx.font = '10pt Calibri';  
  145.    ctx.globalAlpha = 1;  
  146.    /// end step 7) ::::::::::::::::::::::::::::::::::::::  
  147. }  
Here we see the entire method one by one that will be used to draw the chart.

Draw Bar Chart

In this method I will calculate all the data with plot x and y point and draw the rectangle one by one to draw the Bar chart.

  1. function drawBarChart()   
  2. {  
  3.      var XvalPosition = xSpace;  
  4.      widthcalculation = parseInt(((parseInt(chartWidth) - 100) / noOfPlots));  
  5.      colorval = 0;  
  6.      $('#cphBody_DropDownList1 option').each(function () {  
  7.   
  8.          // Draw Xaxis Plots Line and Text   ***********  
  9.          XvalPosition = XvalPosition + widthcalculation;  
  10.          ctx.moveTo(XvalPosition, chartHeight);  
  11.          ctx.lineTo(XvalPosition, chartHeight + 15);  
  12.          ctx.stroke();  
  13.          ctx.fillStyle = "#000000";  
  14.          ctx.font = '10pt Calibri';  
  15.          ctx.fillText('Bar' + parseInt(colorval + 1), XvalPosition - 28, chartHeight + 24);  
  16.   
  17.          //  End Xval Plotting  ************  
  18.   
  19.          //Draw Bar Graph  **************==================********************  
  20.   
  21.          var barRatio = parseInt($(this).val()) / maxDataVal;  
  22.          //alert(ratio)  
  23.          var barfillHeight = parseInt(barRatio * (parseInt(chartHeight - xSpace)));  
  24.          // alert(barHeight)  
  25.          ctx.fillRect(XvalPosition - widthcalculation - 1, chartHeight - 1, widthcalculation + 2, -barfillHeight);  
  26.          ctx.fillStyle = pirChartColor[colorval];  
  27.          //  e.DrawRectangle(B1pen, XvalPosition_Start, Ystartval, XvalPosition_new, YEndval);  
  28.          ctx.fillRect(XvalPosition - widthcalculation, chartHeight, widthcalculation, -barfillHeight);  
  29.   
  30.          //ctx.fillRect(XvalPosition - widthcalculation, yLineHeight, widthcalculation, yLineHeight- parseInt($(this).val()));  
  31.          // *****  
  32.   
  33.          //////            ctx.fillStyle = "#000000";  
  34.          //////            ctx.font = '10pt Calibri';  
  35.          //////            ctx.fillText($(this).val(), XvalPosition - widthcalculation + 4, chartHeight - barfillHeight - 8);  
  36.          ctx.fillStyle = pirChartColor[colorval];  
  37.   
  38.          //END Draw Bar Graph  **************==================********************  
  39.          colorval = colorval + 1;  
  40.      });  
  41.  }  

Draw Line Chart

In this method I will calculate all the data with plot x and y point and draw the line with Dot and Item text to be draw for each Line point.

  1. function drawLineChart()   
  2. {  
  3.   
  4.        // For Drawing Line  
  5.        ctx.lineWidth = 3;  
  6.        var value = $('select#cphBody_DropDownList1 option:selected').val();  
  7.        // alert(value);  
  8.        ctx.beginPath();  
  9.   
  10.        // *************** To Draw the Line and Plot Value in Line  
  11.        ctx.fillStyle = "#FFFFFF";  
  12.        ctx.strokeStyle = '#FFFFFF';  
  13.        ctx.moveTo(getXPlotvalue(0), getYPlotVale(value));  
  14.   
  15.        ctx.fillStyle = "#000000";  
  16.        ctx.font = '12pt Calibri';  
  17.        ctx.fillText(value, getXPlotvalue(0), getYPlotVale(value) - 12);  
  18.   
  19.        var ival = 0;  
  20.        $('#cphBody_DropDownList1 option').each(function () {  
  21.   
  22.            if (ival > 0) 
  23.          {  
  24.                ctx.lineTo(getXPlotvalue(ival), getYPlotVale($(this).val()));  
  25.                ctx.stroke();  
  26.   
  27.                ctx.fillStyle = "#000000";  
  28.                ctx.font = '12pt Calibri';  
  29.                ctx.fillText($(this).val(), getXPlotvalue(ival), getYPlotVale($(this).val()) - 16);  
  30.            }  
  31.            ival = ival + 1;  
  32.            ctx.fillStyle = lineColor;  
  33.            ctx.strokeStyle = lineColor;  
  34.        });  
  35.   
  36.   
  37.   
  38.        // *************** To Draw the Line Dot Cericle  
  39.   
  40.        //For Outer Blue Dot  
  41.   
  42.        ival = 0;  
  43.        $('#cphBody_DropDownList1 option').each(function () {  
  44.            ctx.fillStyle = lineOuterCircleColor;  
  45.            ctx.strokeStyle = lineOuterCircleColor;  
  46.            ctx.beginPath();  
  47.            ctx.arc(getXPlotvalue(ival), getYPlotVale($(this).val()), 7, 0, Math.PI * 2, true);  
  48.            ctx.fill();  
  49.   
  50.            ctx.fillStyle = lineInnerCircleColor;  
  51.            ctx.strokeStyle = lineInnerCircleColor;  
  52.            ctx.beginPath();  
  53.            ctx.arc(getXPlotvalue(ival), getYPlotVale($(this).val()), 4, 0, Math.PI * 2, true);  
  54.            ctx.fill();  
  55.            ival = ival + 1;  
  56.        });  
  57.   
  58.        ctx.lineWidth = 1;  
  59. }  
Draw Pie Chart

The same as for the Bar chart here I will calculate all the points and draw the pie chart using the “arc” method.
  1. using “arc” method.  
  2.   
  3. function drawPieChart()   
  4. {  
  5.   
  6.       var lastend = 0;  
  7.       var XvalPosition = xSpace;  
  8.   
  9.       chartWidth = (canvas.width / 2) - xSpace;  
  10.       chartHeight = (canvas.height / 2) - (xSpace / 2);  
  11.   
  12.       widthcalculation = parseInt(((parseInt(chartWidth) - 100) / noOfPlots));  
  13.   
  14.       //Draw Xaxis Line  
  15.       //-- draw bar X-Axis and Y-Axis Line  
  16.       var XLineStartPosition = xSpace;  
  17.       var yLineStartPosition = xSpace;  
  18.       var yLineHeight = chartHeight;  
  19.       var xLineWidth = chartWidth;  
  20.   
  21.       colorval = 0;  
  22.       var chartTotalResult = getChartTotal();  
  23.   
  24.       $('#cphBody_DropDownList1 option').each(function () 
  25.     {  
  26.           ctx.fillStyle = pirChartColor[colorval];  
  27.           ctx.beginPath();  
  28.           ctx.moveTo(chartWidth, chartHeight);  
  29.           //Here we draw the each Pic Chart arc with values and size.  
  30.           ctx.arc(chartWidth, chartHeight + 6, chartHeight, lastend, lastend +  
  31.             (Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult)), false);  
  32.   
  33.           ctx.lineTo(chartWidth, chartHeight);  
  34.   
  35.           ctx.fill();  
  36.           lastend += Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult);  

  37.           //END Draw Bar Graph  **************==================********************  
  38.           colorval = colorval + 1;  
  39.       });  
  40.   }  
Draw Donut Chart

The same as for the Pie chart here I will calculate all the points and draw the Pie chart using the “arc” method. For the Donut chart to draw a donut shape we use the “donutoutcircle” and “donutInnsercircle” value. Here I will check for the Chart width and height I will draw the donut chart size.
  1. function drawDonutChart()   
  2. {  
  3.      var lastend = 0;  
  4.      var XvalPosition = xSpace;  
  5.   
  6.      chartWidth = (canvas.width / 2) - xSpace;  
  7.      chartHeight = (canvas.height / 2) - (xSpace / 2);  
  8.   
  9.      widthcalculation = parseInt(((parseInt(chartWidth) - 100) / noOfPlots));  
  10.      var donutOutercircle = chartHeight / 2;  
  11.      var donutinnersircle = (chartWidth / 2) + xSpace;  
  12.   
  13.      colorval = 0;  
  14.      var chartTotalResult = getChartTotal();  
  15.   
  16.      var legend1 = 0  
  17.      $('#cphBody_DropDownList1 option').each(function () 
  18.     {  
  19.        
  20.          ctx.fillStyle = pirChartColor[colorval];  
  21.          legend1 += (Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult))  
  22.          //----  
  23.          ctx.beginPath();  
  24.          ctx.moveTo(chartWidth, chartWidth);  
  25.          ctx.arc(chartWidth, chartWidth, donutOutercircle, lastend, legend1, false); // Outer: CCW  
  26.          ctx.arc(chartWidth, chartWidth, donutinnersircle, legend1, lastend, true); // Inner: CW  
  27.          //------  
  28.   
  29.          ctx.fill();  
  30.          lastend += Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult);  
  31.   
  32.          //END Draw Bar Graph  **************==================********************  
  33.          colorval = colorval + 1;  
  34.      });  
  35.  }  
Draw Bubble Chart

The same as for the Line chart we draw the Bubble chart but here use the "arc” method to draw our circle for each item.
  1. // to Draw Bubble Chart  
  2.  function drawBubbleChart() 
  3. {  
  4.   
  5.      // *************** To Draw the Line Dot Cericle  
  6.      ctx.globalAlpha = 0.8;  
  7.      //For Outer Blue Dot  
  8.      var bubbleSize = 40;  
  9.      ival = 0;  
  10.      $('#cphBody_DropDownList1 option').each(function () 
  11.      {  
  12.   
  13.          ctx.fillStyle = pirChartColor[ival];  
  14.          ctx.strokeStyle = pirChartColor[ival];  
  15.          ctx.beginPath();  
  16.          ctx.arc(getXPlotvalue(ival) + 14, getYPlotVale($(this).val()), bubbleSize, bubbleSize, Math.PI * 2, true);  
  17.          ctx.fill();  
  18.          ival = ival + 1;  
  19.      });  
  20.   
  21.      ctx.lineWidth = 1;  
  22.   
  23.  }  
Save Chart

In the save method first I will check for the browser version. If the browser is not IE (that means Chrome or Firefox) then using the “canvas.toDataURL” method I will save the image. Because this method will not work in Internet Explorer. For Internet Explorer use the Ajax post method. I will save the image.

  1. function ShanuSaveImage()   
  2. {  
  3.      var m = confirm("Are you sure to Save ");  
  4.      if (m) 
  5.      {  
  6.          if (navigator.appName == 'Microsoft Internet Explorer'
  7.          {  
  8.   
  9.              var image_NEW = document.getElementById("canvas").toDataURL("image/png");  
  10.              image_NEW = image_NEW.replace('data:image/png;base64,''');  
  11.   
  12.              $.ajax({  
  13.                  type: 'POST',  
  14.                  contentType: 'application/json; charset=utf-8',  
  15.                  url: '/shanuHTML5PIEChart.aspx/SaveImage',  
  16.                  data: '{ "imageData" : "' + image_NEW + '" }',  
  17.                  async: false,  
  18.                  success: function (msg) {  
  19.                      alert(msg.d);  
  20.                  },  
  21.                  error: function () {  
  22.                      alert("Pie Chart Not Saved");  
  23.                  }  
  24.   
  25.              });  
  26.          }  
  27.          else 
  28.          {  
  29.              // save image without file type  
  30.              var canvas = document.getElementById("canvas");  
  31.              document.location.href = canvas.toDataURL("image/png").replace("image/png""image/octet-stream");  
  32.   
  33.              var ImageSave = document.createElement('a');  
  34.              ImageSave.download = "shanuPIEImage.png";  
  35.              ImageSave.href = canvas.toDataURL("image/png").replace("image/png""image/octet-stream");  
  36.              ImageSave.click();  
  37.              alert("Image Saved");  
  38.          }  
  39.      }  
  40.   
  41.  }  
Bind Dropdown List Data from DataTable

In the page Load and in Button Click I will call the “BindDropDownList()” method to populate the Pie Chart values in the DataTable and bind the final result to the Dropdown List.

Here for the simple example I have used the DataTable to populate the data and bind the result to the dropdown list.

You can write your own code to bind the result to the Dropdown list. You can even change the source from the Dropdown List to any control depending on your requirements. The Dropdown list items will be obtained in JavaScript and using the values the Pie chart will be created dynamically.
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     BindDropDownList();  
  4. }  
  5.   
  6. protected void Button1_Click(object sender, EventArgs e)  
  7. {  
  8.     BindDropDownList();  
  9. }  
  10.   
  11. private void BindDropDownList()  
  12. {  
  13.     DataTable dt = new DataTable();  
  14.     dt.Clear();  
  15.     dt.Rows.Clear();  
  16.     dt.Columns.Add("Names");  
  17.     dt.Columns.Add("Frequency");  
  18.     dt.Columns["Frequency"].DataType = Type.GetType("System.Int32");  

  19.     Random random = new Random();             
  20.   
  21.     for (int i = 1; i <=Convert.ToInt32(txtChartCount.Text.Trim()); i++)  
  22.     {  
  23.         DataRow row = dt.NewRow();  
  24.         Int32 value = random.Next(100, 600);  
  25.         row["Names"] = "Bar-" + i.ToString() + " - (" + value+") ";  
  26.         row["Frequency"] = value;  
  27.         dt.Rows.Add(row);  
  28.     }  
  29.     DropDownList1.DataSource = dt;  
  30.     DropDownList1.DataTextField = "Names";  
  31.     DropDownList1.DataValueField = "Frequency";  
  32.     DropDownList1.DataBind();  
  33. }  
Points of Interest

We can use the same logic to create Windows Forms Chart Controls. For example you can see my Pareto Chart control that was created for Windows Forms version at the following link:

http://www.c-sharpcorner.com/UploadFile/asmabegam/pareto-chart-in-C-Sharp/

Working with HTML5 is really fun. I hope you enjoyed reading my article. I will be happy if someone benefits from my article.

Tested Browsers: 
  1. Chrome 
  2. Firefox
  3. IE10
Output


 



Similar Articles