다음을 통해 공유


Draw ASP.Net 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

Note: You can download the Source Code  from the link ** Source Code Download Link** 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.

<SECTION style="border-style: solid; border-width: 2px; width: 800px;">  
<CANVAS HEIGHT="600px" WIDTH="800px" ID="canvas">  
Your browser is not supporting HTML5 Canvas .Upgrade Browser to view this program or check with Chrome or in Firefox.  
</CANVAS>  
</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.

//public Canvas object to use in all the functions.  
//this variable will be used to check for the result of Alert Image display  
var alertCheckValue = 300;  
   
//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.  
var pirChartColor = ["#6CBB3C", "#F87217",  "#EAC117", "#EDDA74", "#CD7F32",  "#CCFB5D", "#FDD017", "#9DC209",  "#E67451", "#728C00", "#617C58",  "#64E986"]; // green Color Combinations  
// var pirChartColor = ["#3090C7", "#BDEDFF", "#78C7C7", "#736AFF", "#7FFFD4", "#3EA99F", "#EBF4FA", "#F9B7FF", "#8BB381", "#BDEDFF", "#B048B5", "#4E387E"]; // Blue Color Combinations  
var lineColor = "#3090C7";  
var lineOuterCircleColor = "#6CBB3C";  
var lineInnerCircleColor = "#FFFFFF";  
   
//declare the Canvas object  
var canvas;  
var chartCTX;  
   
// declare the Border Space,Chart Start X and Y Position;  
var xSpace = 80;  
var ySpace = 80;  
//declare the Chart DrawWidth and Hegith  
var chartWidth, chartHeight;  
   
// declared the Chart Legend Width and Hegit  
var legendWidth, legendHeight;  
   
//declared the Chart data Minimum Value,maximum Value and Noofplots(Bars/Arc and Line points)  
var minDataVal, maxDataVal, noOfPlots;  
   
//here we declare the Image for the Chart legend alert status display.  
var greenImage = new Image();  
var redImage = new Image();  
//Alert Image Size widht and hegith  
var imagesize = 20;  
var maxValdivValue;  
//Here we declare the X,YAxis Font size and Color  
var fotnColor = "#000000";  
var axisfontSize = 10;  
   
var LogoImage = new Image();  
var LogoImgWidth = 120;  
var LogoImgHeight = 70;  
// This arrawy wil be used to draw the Legends   
rect = {};  
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

if ($('#cphBody_rdoColorGreen:checked').val() == "rdoColorGreen")  
{  
}

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.

if ($('# rdoColorGreen:checked').val() == "rdoColorGreen")   
{  
}

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.

function ChangeChartColor()   
{  
   if ($('#cphBody_rdoColorGreen:checked').val() == "rdoColorGreen") 
   {  
         pirChartColor = ["#6CBB3C", "#F87217",  "#EAC117", "#EDDA74", "#CD7F32",  "#CCFB5D", "#FDD017", "#9DC209",  "#E67451", "#728C00", "#617C58",  "#64E986"]; // green Color Combinations  
         lineColor = "#3090C7";  // Blue Color for Line  
         lineOuterCircleColor = "#6CBB3C";  // Green Color for Outer Circle  
   }  
   else
   {  
         pirChartColor = ["#3090C7", "#BDEDFF",  "#78C7C7", "#736AFF", "#7FFFD4",  "#3EA99F", "#EBF4FA", "#F9B7FF",  "#8BB381", "#BDEDFF", "#B048B5",  "#4E387E"]; // Blue Color Combinations  
         lineColor = "#F87217";   // Orange Color for the Line  
         lineOuterCircleColor = "#F70D1A ";  // Red Color for the outer circle  
   }  
}

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.

function getXPlotvalue(val)   
{  
    return (Math.round((chartWidth - xSpace) / noOfPlots)) * val + (xSpace * 1.5)-24;  
}  
   
// Return the y pixel for a graph point  
function getYPlotVale(val) 
{  
    return chartHeight - (((chartHeight - xSpace) / maxDataVal) * val);  
}

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.)

// This function is used to draw the Legend  
function drawLengends() 
{  
    ctx.fillStyle = "#7F462C";   
    ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);  
    //Drawing Inner White color Rectange with in Above brown rectangle to plot all the Lables with color,Text and Value.  
    ctx.fillStyle = "#FFFFFF";   
    rectInner.startX = rect.startX + 1;  
    rectInner.startY = rect.startY + 1;  
    rectInner.w = rect.w - 2;  
    rectInner.h = rect.h - 2;  
    ctx.fillRect(rectInner.startX, rectInner.startY, rectInner.w, rectInner.h);  
    labelBarX = rectInner.startX + 4;  
    labelBarY = rectInner.startY + 4;  
    labelBarWidth = rectInner.w - 10;  
    labelBarHeight = (rectInner.h / noOfPlots) - 5;  
    colorval = 0;  
    // here to draw all the rectangle for Lables with Image display  
    $('#cphBody_DropDownList1 option').each(function () 
    {  
        ctx.fillStyle = pirChartColor[colorval];  
        ctx.fillRect(labelBarX, labelBarY, labelBarWidth, labelBarHeight);  
     // 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.  
        if ($('#cphBody_rdoAlaramOn:checked').val() == "rdoAlaramOn") 
        {  
           // Here we can see fo ever chart value we check with the condition .we have initially declare the alertCheckValue as 300.  
           //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.  
           //user can change this to your requiremnt if needed.This is optioan function for the Pie Chart.  
           if (parseInt($(this).val()) >= alertCheckValue) 
           {  
               ctx.drawImage(greenImage, labelBarX, labelBarY + (labelBarHeight / 3) - 4, imagesize, imagesize);  
           }  
           else
           {  
               ctx.drawImage(redImage, labelBarX, labelBarY + (labelBarHeight / 3) - 4, imagesize, imagesize);  
           }  
        }  
        //Draw the Pie Chart Label text and Value  
        ctx.fillStyle = "#000000";   
        ctx.font = '10pt Calibri';  
        ctx.fillText($(this).text(), labelBarX + imagesize + 2, labelBarY + (labelBarHeight / 2));  
   
        // To Increment and draw the next bar ,label Text and Alart Image.  
        labelBarY = labelBarY + labelBarHeight + 4;  
        //  labelTextYXVal = labelBarY + labelBarHeight - 4;  
   
        colorval = colorval + 1;  
    });  
}

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.  
// This is the main function to darw the Charts  
function drawChart() 
{  
    ChangeChartColor();  
    // asign the images path for both Alert images  
    greenImage.src = '../images/Green.png';  
    redImage.src = '../images/Red.png';  
    LogoImage.src = '../images/shanu.jpg';  
    // 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.  
    minDataVal = $('#cphBody_hidListMin').val();  
    maxDataVal = $('#cphBody_hidListMax').val();  
    // Total no of plots we are going to draw.  
    noOfPlots = $("#cphBody_DropDownList1 option").length;  
    maxValdivValue = Math.round((maxDataVal / noOfPlots));  
    //storing the Canvas Context to local variable ctx.This variable will be used to draw the Pie Chart  
    canvas = document.getElementById("canvas");  
    ctx = canvas.getContext("2d");  
    //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.  
    ctx.globalAlpha = 1;  
    ctx.fillStyle = "#000000";   
    ctx.strokeStyle = '#000000';   
    //Every time we clear the canvas and draw the chart   
    ctx.clearRect(0, 0, canvas.width, canvas.height);  
   
    //If need to draw with out legend for the Line Chart  
    chartWidth = canvas.width - xSpace;  
    chartHeight = canvas.height - ySpace;  
    //  step 1) Draw legend $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$########################  
    if ($('#cphBody_chkLegend:checked').val() == "on") 
    {  
         chartWidth = canvas.width - ((canvas.width / 3) - (xSpace / 2));  
         chartHeight = canvas.height - ySpace - 10;  
   
         legendWidth = canvas.width - ((canvas.width / 3) - xSpace);  
         legendHeight = ySpace;  
   
         rect.startX = legendWidth;  
         rect.startY = legendHeight;  
         rect.w = canvas.width / 3 - xSpace - 10;  
         rect.h = canvas.height - ySpace - 10;  
         //In this method i will draw the legend with the Alert Image.  
         drawLengends();  
     }  
     // end step 1) $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$  
     var chartMidPosition = chartWidth / 2 - 60;  
   
      ////        //If need to draw with legend  
      ////        chartWidth = canvas.width - ((canvas.width / 3) - (xSpace / 2));  
      ////        chartHeight = canvas.height - ySpace - 10;  
   
      // Step 2 ) +++++++++++++ To Add Chart Titel and  Company Logo  
      //To Add Logo to Chart  
   
      var logoXVal = canvas.width - LogoImgWidth - 10;   
      var logolYVal = 0;  
   
      //here we draw the Logo for teh chart and i have used the alpha to fade and display the Logo.  
      ctx.globalAlpha = 0.6;  
   
      ctx.drawImage(LogoImage, logoXVal, logolYVal, LogoImgWidth, LogoImgHeight);  
   
      ctx.globalAlpha = 1;  
   
      ctx.font = '22pt Calibri';  
      ctx.fillStyle = "#15317E";   
      ctx.fillText($('#cphBody_txtTitle').val(), chartMidPosition, chartHeight + 60);  
   
   
      ctx.fillStyle = "#000000";   
      ctx.font = '10pt Calibri';  
   
      // end step 2) +++++++++++ End of Title and Company Logo Add  
   
      // Step 3 ) +++++++++++++ toDraw the X-Axis and Y-Axis  
    
      //  >>>>>>>>> Draw Y-Axis and X-Axis Line(Horizontal Line)  
      // Draw the axises  
     ctx.beginPath();  
     ctx.moveTo(xSpace, ySpace);  
     // first Draw Y Axis  
     ctx.lineTo(xSpace, chartHeight);  
   
     // Next draw the X-Axis  
     ctx.lineTo(chartWidth, chartHeight);  
     ctx.stroke();  
     //  >>>>>>>>>>>>> End of X-Axis Line Draw  
     //end step 3) +++++++++++++++++++++++  
   
   
     // Step 4) <<<<<<<<<<<<<<<<<<<<<<< To Draw X - Axis Plot Values <<<<<<<<<<<<< }}}}}}  
     // Draw the X value texts  
     // --->>>>>>>>>>>>  for the Bar Chart i have draw the X-Axis plot in  drawBarChart  
     //  <<<<<<<<<<<<<<<<<<<<<<< End of X Axis Draw  
   
     // end Step 4) <<<<<<<<<<<<<<<<<<<<<<<  
   
     // Step 5){{{{{{{{{{{{  
     // {{{{{{{{{{{{{To Draw the Y Axis Plot Values}}}}}}}}}}}}}}  
     var vAxisPoints = 0;  
     var max = maxDataVal;  
     max += 10 - max % 10;  
     for (var i = 0; i <= maxDataVal; i += maxValdivValue) 
    {  
    
       ctx.fillStyle = fotnColor;  
       ctx.font = axisfontSize + 'pt Calibri';          
       ctx.fillText(i, xSpace - 40, getYPlotVale(i));  
   
       //Here we draw the Y-Axis point line  
       ctx.beginPath();  
       ctx.moveTo(xSpace, getYPlotVale(i));  
   
       ctx.lineTo(xSpace - 10, getYPlotVale(i));  
       ctx.stroke();  
       vAxisPoints = vAxisPoints + maxValdivValue;  
    
    }  
   
   //{{{{{{{{{{{{{{ End of Y- Axis Plot Values  
   
   //end  Step 5) {{{{{{{{{{{{{{{{{{  
   
   
   //Step 5) *********************************************************  
   //Function to Draw our Chart here we can Call/Bar Chart/Line Chart or Pie Chart  
   
   // to Draw Bar Chart  
   drawBarChart();  
  
   // to Draw line Chart  
   drawLineChart();  
   // end step 6) **************  
   
   //Step 7)  :::::::::::::::::::: to add the Water mark Text  
   
   // Here add the Water mark text at center of the chart  
   ctx.globalAlpha = 0.1;  
   ctx.font = '86pt Calibri';     
   ctx.fillStyle = "#000000";   
   ctx.fillText($('#cphBody_txtWatermark').val(), chartMidPosition - 40, chartHeight / 2);  
   
   ctx.font = '10pt Calibri';  
   ctx.globalAlpha = 1;  
   /// end step 7) ::::::::::::::::::::::::::::::::::::::  
}

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.

function drawBarChart()   
{  
     var XvalPosition = xSpace;  
     widthcalculation = parseInt(((parseInt(chartWidth) - 100) / noOfPlots));  
     colorval = 0;  
     $('#cphBody_DropDownList1 option').each(function () {  
   
         // Draw Xaxis Plots Line and Text   ***********  
         XvalPosition = XvalPosition + widthcalculation;  
         ctx.moveTo(XvalPosition, chartHeight);  
         ctx.lineTo(XvalPosition, chartHeight + 15);  
         ctx.stroke();  
         ctx.fillStyle = "#000000";   
         ctx.font = '10pt Calibri';  
         ctx.fillText('Bar' + parseInt(colorval + 1), XvalPosition - 28, chartHeight + 24);  
   
         //  End Xval Plotting  ************  
   
         //Draw Bar Graph  **************==================********************  
   
         var barRatio = parseInt($(this).val()) / maxDataVal;  
         //alert(ratio)  
         var barfillHeight = parseInt(barRatio * (parseInt(chartHeight - xSpace)));  
         // alert(barHeight)  
         ctx.fillRect(XvalPosition - widthcalculation - 1, chartHeight - 1, widthcalculation + 2, -barfillHeight);  
         ctx.fillStyle = pirChartColor[colorval];  
         //  e.DrawRectangle(B1pen, XvalPosition_Start, Ystartval, XvalPosition_new, YEndval);  
         ctx.fillRect(XvalPosition - widthcalculation, chartHeight, widthcalculation, -barfillHeight);  
   
         //ctx.fillRect(XvalPosition - widthcalculation, yLineHeight, widthcalculation, yLineHeight- parseInt($(this).val()));  
         // *****  
   
         //////            ctx.fillStyle = "#000000";  
         //////            ctx.font = '10pt Calibri';  
         //////            ctx.fillText($(this).val(), XvalPosition - widthcalculation + 4, chartHeight - barfillHeight - 8);  
         ctx.fillStyle = pirChartColor[colorval];  
   
         //END Draw Bar Graph  **************==================********************  
         colorval = colorval + 1;  
     });  
 }


**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.

function drawLineChart()   
{  
   
       // For Drawing Line  
       ctx.lineWidth = 3;  
       var value = $('select#cphBody_DropDownList1 option:selected').val();  
       // alert(value);  
       ctx.beginPath();  
   
       // *************** To Draw the Line and Plot Value in Line  
       ctx.fillStyle = "#FFFFFF";   
       ctx.strokeStyle = '#FFFFFF';   
       ctx.moveTo(getXPlotvalue(0), getYPlotVale(value));  
   
       ctx.fillStyle = "#000000";   
       ctx.font = '12pt Calibri';  
       ctx.fillText(value, getXPlotvalue(0), getYPlotVale(value) - 12);  
   
       var ival = 0;  
       $('#cphBody_DropDownList1 option').each(function () {  
   
           if (ival > 0) 
         {  
               ctx.lineTo(getXPlotvalue(ival), getYPlotVale($(this).val()));  
               ctx.stroke();  
   
               ctx.fillStyle = "#000000";   
               ctx.font = '12pt Calibri';  
               ctx.fillText($(this).val(), getXPlotvalue(ival), getYPlotVale($(this).val()) - 16);  
           }  
           ival = ival + 1;  
           ctx.fillStyle = lineColor;  
           ctx.strokeStyle = lineColor;  
       });  
   
   
   
       // *************** To Draw the Line Dot Cericle  
   
       //For Outer Blue Dot  
   
       ival = 0;  
       $('#cphBody_DropDownList1 option').each(function () {  
           ctx.fillStyle = lineOuterCircleColor;  
           ctx.strokeStyle = lineOuterCircleColor;  
           ctx.beginPath();  
           ctx.arc(getXPlotvalue(ival), getYPlotVale($(this).val()), 7, 0, Math.PI * 2, true);  
           ctx.fill();  
   
           ctx.fillStyle = lineInnerCircleColor;  
           ctx.strokeStyle = lineInnerCircleColor;  
           ctx.beginPath();  
           ctx.arc(getXPlotvalue(ival), getYPlotVale($(this).val()), 4, 0, Math.PI * 2, true);  
           ctx.fill();  
           ival = ival + 1;  
       });  
   
       ctx.lineWidth = 1;  
}

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.

using “arc” method.  
   
function drawPieChart()   
{  
   
      var lastend = 0;  
      var XvalPosition = xSpace;  
   
      chartWidth = (canvas.width / 2) - xSpace;  
      chartHeight = (canvas.height / 2) - (xSpace / 2);  
   
      widthcalculation = parseInt(((parseInt(chartWidth) - 100) / noOfPlots));  
   
      //Draw Xaxis Line  
      //-- draw bar X-Axis and Y-Axis Line  
      var XLineStartPosition = xSpace;  
      var yLineStartPosition = xSpace;  
      var yLineHeight = chartHeight;  
      var xLineWidth = chartWidth;  
   
      colorval = 0;  
      var chartTotalResult = getChartTotal();  
   
      $('#cphBody_DropDownList1 option').each(function () 
    {  
          ctx.fillStyle = pirChartColor[colorval];  
          ctx.beginPath();  
          ctx.moveTo(chartWidth, chartHeight);  
          //Here we draw the each Pic Chart arc with values and size.  
          ctx.arc(chartWidth, chartHeight + 6, chartHeight, lastend, lastend +  
            (Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult)), false);  
   
          ctx.lineTo(chartWidth, chartHeight);  
   
          ctx.fill();  
          lastend += Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult);  
 
          //END Draw Bar Graph  **************==================********************  
          colorval = colorval + 1;  
      });  
  }

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.

function drawDonutChart()   
{  
     var lastend = 0;  
     var XvalPosition = xSpace;  
   
     chartWidth = (canvas.width / 2) - xSpace;  
     chartHeight = (canvas.height / 2) - (xSpace / 2);  
   
     widthcalculation = parseInt(((parseInt(chartWidth) - 100) / noOfPlots));  
     var donutOutercircle = chartHeight / 2;  
     var donutinnersircle = (chartWidth / 2) + xSpace;   
   
     colorval = 0;  
     var chartTotalResult = getChartTotal();  
   
     var legend1 = 0  
     $('#cphBody_DropDownList1 option').each(function () 
    {  
        
         ctx.fillStyle = pirChartColor[colorval];  
         legend1 += (Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult))  
         //----  
         ctx.beginPath();  
         ctx.moveTo(chartWidth, chartWidth);  
         ctx.arc(chartWidth, chartWidth, donutOutercircle, lastend, legend1, false); // Outer: CCW  
         ctx.arc(chartWidth, chartWidth, donutinnersircle, legend1, lastend, true); // Inner: CW  
         //------  
   
         ctx.fill();  
         lastend += Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult);  
   
         //END Draw Bar Graph  **************==================********************  
         colorval = colorval + 1;  
     });  
 }


**
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.

/ to Draw Bubble Chart  
 function drawBubbleChart() 
{  
   
     // *************** To Draw the Line Dot Cericle  
     ctx.globalAlpha = 0.8;  
     //For Outer Blue Dot  
     var bubbleSize = 40;  
     ival = 0;  
     $('#cphBody_DropDownList1 option').each(function () 
     {  
   
         ctx.fillStyle = pirChartColor[ival];  
         ctx.strokeStyle = pirChartColor[ival];  
         ctx.beginPath();  
         ctx.arc(getXPlotvalue(ival) + 14, getYPlotVale($(this).val()), bubbleSize, bubbleSize, Math.PI * 2, true);  
         ctx.fill();  
         ival = ival + 1;  
     });  
   
     ctx.lineWidth = 1;  
   
 }


**
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.

function ShanuSaveImage()   
{  
     var m = confirm("Are you sure to Save ");  
     if (m) 
     {  
         if (navigator.appName == 'Microsoft Internet Explorer') 
         {  
   
             var image_NEW = document.getElementById("canvas").toDataURL("image/png");  
             image_NEW = image_NEW.replace('data:image/png;base64,', '');  
   
             $.ajax({  
                 type: 'POST',   
                 contentType: 'application/json; charset=utf-8',  
                 url: '/shanuHTML5PIEChart.aspx/SaveImage',  
                 data: '{ "imageData" : "'  + image_NEW + '" }',  
                 async: false,  
                 success: function  (msg) {  
                     alert(msg.d);  
                 },  
                 error: function  () {  
                     alert("Pie Chart Not Saved");  
                 }  
   
             });  
         }  
         else
         {  
             // save image without file type  
             var canvas = document.getElementById("canvas");  
             document.location.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");  
   
             var ImageSave = document.createElement('a');  
             ImageSave.download = "shanuPIEImage.png";  
             ImageSave.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");  
             ImageSave.click();  
             alert("Image Saved");  
         }  
     }  
   
 }

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.

protected void Page_Load(object sender, EventArgs e)  
{  
    BindDropDownList();  
}  
   
protected void Button1_Click(object sender, EventArgs e)  
{  
    BindDropDownList();  
}  
   
private void BindDropDownList()  
{  
    DataTable dt = new  DataTable();  
    dt.Clear();  
    dt.Rows.Clear();  
    dt.Columns.Add("Names");  
    dt.Columns.Add("Frequency");  
    dt.Columns["Frequency"].DataType = Type.GetType("System.Int32");  
 
    Random random = new  Random();             
   
    for (int i = 1; i <=Convert.ToInt32(txtChartCount.Text.Trim()); i++)  
    {  
        DataRow row = dt.NewRow();  
        Int32 value = random.Next(100, 600);  
        row["Names"] = "Bar-" + i.ToString() + " - (" + value+") ";  
        row["Frequency"] = value;  
        dt.Rows.Add(row);  
    }  
    DropDownList1.DataSource = dt;  
    DropDownList1.DataTextField = "Names";   
    DropDownList1.DataValueField = "Frequency";   
    DropDownList1.DataBind();  
}

**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