Click here to Skip to main content
15,885,782 members
Articles / Web Development / HTML

Draw ASP.NET Chart using HTML5 and jQuery

Rate me:
Please Sign up or sign in to vote.
4.73/5 (27 votes)
14 Jul 2015CPOL9 min read 73.9K   5.1K   73   7
How to use ASP.NET, HTML5 and jQuery to draw our charts
In this article, we will see using ASP.NET, HTML5 and jQuery how to draw our charts like Line, Bar, Pie, Donut and Bubble Chart.

Image 1

Introduction

In my previous article, Web Painting Tool Using HTML 5 CANVAS in ASP.NET, I explained how to create a simple Web Painting tool using HTML5 and jQuery. I used the program with the help of few reference websites to draw a simple Chart using HTML5 and jQuery.

There might be some question about why we need to draw our own Chart as there are lots of free and third party Charts available.

The answer to this question is that even if there are lots of free Chart controls available, sometimes all the chart controls will not fulfill our requirement.

For example, if we want to add our own watermarks to our Chart, if we want to display our own alert Status Image Display, or if we want to add our Company Logo to Chart, etc.

It will be hard to find the Chart controls with all other extra requirement. The Customization will not be possible with other Chart controls. Think if we draw and design our own Chart controls and use that in our projects. There are no limitations to add all our features to draw and design our own Chart. Here, the limitation is up to our imagination.

For this reason, I thought of drawing a Chart with the below features using ASP.NET, HTML5 and jQuery.

In the source code zip file, you can find both Visual Studio 2010 and Visual Studio 2013 solutions .You can use any solution as per your Visual Studio version.

In this article, we will see how to draw the following charts using HTML5 and jQuery:

  1. Line Chart
  2. Bar Chart
  3. Line & Bar Chart
  4. Pie Chart
  5. Donut Chart
  6. Bubble Chart

MY BAR Chart Features

All the below features will be used for all chart types. We can see one by one in the code part.

Image 2

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 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 Water Mark 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 his 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.

What Is 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 two 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

User can enable or disable the display of Legend for the Chart using the check box. If the “Show Legend“ Checkbox is checked, then the chart will be displayed with 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.

Using the Code

Step 1: Create New ASP.NET Web Project

Click Start Program, 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.

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

  1. Script Global variable: First, add the global variable which needs to be used to draw chart inside script tag.

    I have commented the line before for each variable about its use. Here, ChartWidth and chartHeight variable will be used to store and draw the Chart width and height depend on the Canvas size.

    JavaScript
    //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 Height
    var chartWidth, chartHeight;
    
    // declare the Chart Legend Width and Height
    var legendWidth, legendHeight;
    
    //declare 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 width and height
    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 array will be used to draw the Legends
    rect = {};
    rectInner = {};
    

    “Note: I have used the Master pages so in script before each control, I will use the ContentPlaceHolderID.

    For example, my green color theme radio button id is rdoColorGreen. But for jQuery, it will be used like this cphBody_rdoColorGreen.

    For example, if we use master page, then we add ContentPlaceHolderID like this in script.

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

    If we have not used the master page and we draw chat in our webform without including the master page, then we need to remove the contentploceholder id like this:

    JavaScript
    if ($('# rdoColorGreen:checked').val() == "rdoColorGreen") {
    }
  2. Chart Color Theme: In this method, depending on the user color selection checked from the radio button, I will select the Color Array to fill the color for each plots. This is a common function which can be used to draw any chart like Line, bar, Pie, Donut, etc.
    JavaScript
    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 which can be used to draw any chart like Line, bar, Pie, Donut, etc.
    JavaScript
    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 label with color and add label text and Alert Image inside the label. This is a common function which can be used to draw any chart like Line, bar, Pie, Donut, etc. (In Line chart, I don’t use this Legend as line chart is not required for the Label display.)
    JavaScript
    // 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 Rectangle with in above brown rectangle
        //to plot all the Labels 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 Labels 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 for ever chart value we check with the condition.
                // We have initially declare the alertCheckValue as 300.
                // so if the Chart Plot value is Greater than or
                // equal to the check value
                // then we display the Green Image else we display the Red Image.
                // user can change this to your requirement if needed.
                // This is optional 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 Alert Image.
            labelBarY = labelBarY + labelBarHeight + 4;
            //  labelTextYXVal = labelBarY + labelBarHeight - 4;
            colorval = colorval + 1;
        });
    }
    
  5. Draw Chart: This is the main method. In button Draw Chart Image button clicks, I will call this method first, from this method, I will call other methods as per requirement.

    In this method, I have explained in the comment before each code. This method has five 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 necessary variables like Item Maximum Value, Item total Count, Chart Width, Chart Height, legend Width, Legend height, etc.
    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 which needs to be drawn as 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 line chart, I will call the “drawLineChart()” method, etc.
    7. Draw the Water Mark text for the chart.
    JavaScript
    // This is the main function to draw the Charts
    
            function drawChart() {
                ChangeChartColor();
                // assign the images path for both Alert images
                greenImage.src = '../images/Green.png';
                redImage.src = '../images/Red.png';
                LogoImage.src = '../images/shanu.jpg';
                // Get the minimum and maximum value.here i have used the hidden field 
                // from code behind which 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% opacity 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 Title and  Company Logo
                //To Add Logo to Chart
                var logoXVal = canvas.width - LogoImgWidth - 10;
                var logolYVal = 0;
                //here we draw the Logo for the 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 axes
                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 which will be used to draw 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.

    JavaScript
    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;
                    var barfillHeight = parseInt(barRatio * (parseInt(chartHeight - xSpace)));
                    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 drawn for each line point.

    JavaScript
    function drawLineChart() {
    
                // For Drawing Line
    
                ctx.lineWidth = 3;
                var value = $('select#cphBody_DropDownList1 option:selected').val();
                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 Circle
                //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: same like the bar chart, here I will calculate for all the points and draw the pie chart using “arc” method.

    JavaScript
    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: same like the pie chart. Here, I will calculate for all the points and draw the pie chart using “arc” method. For the Donut chart to draw 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.

    JavaScript
    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: same like the line chart, we draw the Bubble chart, but here use the "arc” method to draw our circle for each item.

    JavaScript
    // to Draw Bubble Chart
    
            function drawBubbleChart() {
                // *************** To Draw the Line Dot Circle
                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;
            }
  6. 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”, then using the Ajax post method, I will save the image.
    JavaScript
    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");
                    }
                }
            }
  7. 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 DataTable and bind the final result to the Dropdown List.

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

    You can write your own code to bind the result to Dropdown list. Even you can change the source from Dropdown List to any control as per your requirements.

    This Dropdown list items will be got in JavaScript and using the values, the pie chart will be created dynamically.

    C#
    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();  
            }

Tested Browsers

  • Chrome
  • Firefox
  • IE10

Output

Line Chart

Image 3

Bubble Chart

Image 4

Donut Chart

Image 5

Points of Interest

We can use the same logic to create Winform version Chart Controls. For example, you can see my Pareto Chart control which was created for Windows form version.

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

History

  • 2nd April, 2015: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

 
GeneralMy vote. Pin
Member 1135189320-Jul-15 0:09
Member 1135189320-Jul-15 0:09 
You are my teacher, shanu. while-learning Wink | ;)
GeneralRe: My vote. Pin
syed shanu20-Jul-15 13:31
mvasyed shanu20-Jul-15 13:31 
QuestionCan you elaborate the updates in history? Pin
super15-Jul-15 4:40
professionalsuper15-Jul-15 4:40 
QuestionID mangling Pin
Sinisa Hajnal3-Apr-15 10:20
professionalSinisa Hajnal3-Apr-15 10:20 
QuestionGreat Effort. My Vote 5! Pin
Priyank Modi3-Apr-15 4:27
Priyank Modi3-Apr-15 4:27 
QuestionMy Vote of 5. Pin
aarif moh shaikh2-Apr-15 19:12
professionalaarif moh shaikh2-Apr-15 19:12 
AnswerRe: My Vote of 5. Pin
Divyam Sharma2-Apr-15 19:13
professionalDivyam Sharma2-Apr-15 19:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.