Simple Piechart in HTML5 and Javascript

piejs

I created a little pie-chart component in Javascript for anyone who wants to spice up the HTML5 webs-site.

Basically the requirements are that you define the slices like this:

    
            var slices = {
                "percentages": [25,20,20,5,30],
                "colors": ['gray', 'green', 'blue', 'pink', 'orange'],
            }

            var piechart  = Object.create(PieChart);
            piechart.segmentMode = false;
            piechart.drawPieChart(slices, 'piechart1');

The slices object contains two arrays in it. The first array is a list of the percentages, and the second array contains the corresponding colors. Create the pie chart as a variable via Object.create, and call drawPieChart(..) method passing in the slices object, and a string which is the id of a canvas on your page.

There are two modes.

  • Standard Pie Chart – a basic pie chart with black outline.
  • Segment Pie Chart – the center is hollowed out giving it a slick looking feel. To use this mode just write piechart.segmentMode = true.

Here is the Piechart component code :

       
       var PieChart = {

                drawPieChart: function (slices, id) {

                    var percentElements = slices.percentages;
                    var colorElements = slices.colors;

                    var canvas = document.getElementById(id);
                    var context = canvas.getContext("2d");

                    var centerX = canvas.width / 2;
                    var centerY = canvas.height / 2;
                    var radius = 80;

                    context.beginPath();
                    var endAngle = 2 * Math.PI

                    var lastAngle = 0;

                    for (var i = 0; i < percentElements.length; i++) {
                        var percent = percentElements[i];
                        var color = colorElements[i];

                        var currentSegment = endAngle * (percent/100);
                        var currentAngle = currentSegment + lastAngle;

                        context.beginPath();
                        context.moveTo(centerX, centerY)
                        context.arc(centerX, centerY, radius, lastAngle, currentAngle, false);
                        context.closePath();

                        lastAngle = lastAngle + currentSegment;

                        context.fillStyle = color;
                        context.fill();

                        if (this.segmentMode) {
                            context.lineWidth = 2;
                            context.strokeStyle = 'white';

                        }else {
                            context.lineWidth = 1;
                            context.strokeStyle = 'black';

                        }
                        context.stroke();
                        context.fill();
                    }
                    if (this.segmentMode) {

                        context.beginPath();
                        context.fillStyle = 'white';
                        context.arc(centerX, centerY, radius - 20, 0, 2 * Math.PI, false);
                        context.fill();
                    }
                }
            }

There is some basic maths involved in creating the pie chart. The most odd thing is that in HTML5 you do not define the angles from 360 degrees, but as a percent of 2 * PIE.

There is no legend in this component, but it would be pretty easy to create. Given a table element with id legend, we can write some code like this to show the colors in a table.

          
var slices = {
                "percentages": [25,20,20,5,30],
                "colors": ['gray', 'green', 'blue', 'pink', 'orange'],
                "elements": ['banana', 'clock', 'beetroot', 'planet', 'ball']
            }

            var legend = document.getElementById('legend');

            for (var i = 0; i < slices.percentages.length; i++) {

                var tr = document.createElement('tr');

                legend.appendChild(tr);

                var p = slices.elements[i];
                var c = slices.colors[i];

                var td1 = document.createElement('td');
                var td2 = document.createElement('td');

                tr.appendChild(td1);
                tr.appendChild(td2);

                td1.innerHTML = slices.elements[i];
                td2.style.background = slices.colors[i];
                td2.style.width = '40px';
            }

The complete code for the image at the top of the page is shown below. You may use it any way you wish. Just remember it will only work in a modern browser with HTML5 support suh as the latest browser from Chrome or Firefox.

<head>
    <script>
        window.onload = function() {

            var PieChart = {

                drawPieChart: function (slices, id) {

                    var percentElements = slices.percentages;
                    var colorElements = slices.colors;

                    var canvas = document.getElementById(id);
                    var context = canvas.getContext("2d");

                    var centerX = canvas.width / 2;
                    var centerY = canvas.height / 2;
                    var radius = 80;

                    context.beginPath();
                    var endAngle = 2 * Math.PI

                    var lastAngle = 0;

                    for (var i = 0; i < percentElements.length; i++) {
                        var percent = percentElements[i];
                        var color = colorElements[i];

                        var currentSegment = endAngle * (percent/100);
                        var currentAngle = currentSegment + lastAngle;

                        context.beginPath();
                        context.moveTo(centerX, centerY)
                        context.arc(centerX, centerY, radius, lastAngle, currentAngle, false);
                        context.closePath();

                        lastAngle = lastAngle + currentSegment;

                        context.fillStyle = color;
                        context.fill();

                        if (this.segmentMode) {
                            context.lineWidth = 2;
                            context.strokeStyle = 'white';

                        }else {
                            context.lineWidth = 1;
                            context.strokeStyle = 'black';

                        }
                        context.stroke();
                        context.fill();
                    }
                    if (this.segmentMode) {

                        context.beginPath();
                        context.fillStyle = 'white';
                        context.arc(centerX, centerY, radius - 20, 0, 2 * Math.PI, false);
                        context.fill();
                    }
                }
            }

            var slices = {
                "percentages": [25,20,20,5,30],
                "colors": ['gray', 'green', 'blue', 'pink', 'orange'],
                "elements": ['banana', 'clock', 'beetroot', 'planet', 'ball']
            }

            var piechart  = Object.create(PieChart);
            piechart.segmentMode = false;
            piechart.drawPieChart(slices, 'piechart1');

            var slices = {
                "percentages": [25,20,20,5,30],
                "colors": ['gray', 'green', 'blue', 'pink', 'orange'],
                "elements": ['banana', 'clock', 'beetroot', 'planet', 'ball']
            }

            var piechart  = Object.create(PieChart);
            piechart.segmentMode = true;
            piechart.drawPieChart(slices, 'piechart2');

            var legend = document.getElementById('legend');

            for (var i = 0; i < slices.percentages.length; i++) {

                var tr = document.createElement('tr');

                legend.appendChild(tr);

                var p = slices.elements[i];
                var c = slices.colors[i];

                var td1 = document.createElement('td');
                var td2 = document.createElement('td');

                tr.appendChild(td1);
                tr.appendChild(td2);

                td1.innerHTML = slices.elements[i];
                td2.style.background = slices.colors[i];
                td2.style.width = '40px';
            }
        }
    </script>
</head>
    <body>
        <canvas id='piechart1' width='200px' height='200px'></canvas>
        <canvas id='piechart2' width='200px' height='200px'></canvas>
        <table id='legend'></table>
    </body>
</html>

Enjoy! Please leave a Comment!


Posted in JavaScript | Tagged , , | 4 Comments

4 Responses to Simple Piechart in HTML5 and Javascript

  1. ikram says:

    i need “ilz_test.css ” to try it

  2. Rester says:

    where in the code can you change the bars percentage.

    • felixzacat says:

      in the slices object, under percentages property.

      var slices = {
      “percentages”: [25,20,20,5,30],
      “colors”: ['gray', 'green', 'blue', 'pink', 'orange'],
      “elements”: ['banana', 'clock', 'beetroot', 'planet', 'ball']
      }

  3. M. Ghoshal says:

    If I want to omit the doughnut chart what should I do?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

THREE_COLUMN_PAGE