Search code examples
javascripthtmlraphaelgraphael

Raphael chart, update and replace


I have a pie chart created with raphael. I have a form checkbox that when clicked I want to attach 'effects' to the pie. This example is trying to attach an inner glow with inGlowFun() by creating a circle after it with a gradient.

function allPie(){       

   var pie;     

        Raphael.fn.renderPie = function(cx,cy,r,values,total) {

            var canvas = this, 
                radian = Math.PI / 180,
                chart = this.set();

            function createSlice(cx, cy, r, startAngle, endAngle, params) {
                var x1 = cx + r * Math.cos(-startAngle * radian),
                    x2 = cx + r * Math.cos(-endAngle * radian),
                    y1 = cy + r * Math.sin(-startAngle * radian),
                    y2 = cy + r * Math.sin(-endAngle * radian);


                return canvas.path(["M", cx, cy, "L", x1, y1, "A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2, "z"]).attr(params);
            }




            var angle = 90,
                process = function (j) {

                        var value = parseInt(values[j].spend, 10),
                        angleplus = 360 * value / total,
                        p = createSlice(cx, cy, r, angle - angleplus, angle, {fill: values[j].pieColour, stroke: "#FFF", "stroke-width": 1});

                    values[j].slice = p;    

                    angle -= angleplus;
                    chart.push(p);          
                };


            function glowFun(){
            canvas.circle(cx, cy, 140).attr({fill:"r#fff-#fff:96-#CCC", "stroke-width": 0});
            } 



            // creating each pie slice
            for (var i = 0, ii = values.length; i < ii; i++) {
                process(i);
            }
            //create inner gradient
            function hollowFun(){
            canvas.circle(cx, cy, 120).attr({fill:"85-#fff-#CCC", "stroke-width": 20, "stroke": "#FFF", 'opacity': 0.000001} );
            }




            // inner glow (I admit this is a bit of a hack but it keeps it simple)
            function inGlowFun(){
           canvas.circle(cx, cy, 55).attr({fill:"r#fff-#fff:85-#CCC", "stroke-width": 2, "stroke": "#FFF"});
            }
            if(box.checked){
            inGlowFun();
            }

            // returning the whole set of nodes for interactions later
            return chart;

        };







        // creating a namespace for this code so that anything we create won't effect other JavaScript on the page
        var dotNet = window.dotNet || {};








        /*
        a function that parses the data contained in the data table, creates the Raphaël object we're drawing too and calls our Raphaël plug-in
            $source - reference to the data source (an HTML table in this example)
            $container - reference to the HTML element we're creating the chart inside
        */    
        dotNet.makePie = function($source, $container, pie) {    
            var pie;
            /*
            few constannt variables for this function
                pieData - an empty array that will hold an object for each section
                totalSpend - the grand total of all the rows (calculated via code for greater accuracy)
            */
            var pieData = [],
                totalSpend = 0;


            /* 
            function to parse each table row, create HTML and attach events
                i - index of the iteraction
            */
            function prepare(i) {

                /*
                variables used for each call
                    row - jQuery object of the current table row
                    values - an empty object that will be filled with data and references associated with each row
                    head - jQuery object used to reference the th of the current row
                */
                var row = $(this),
                    values = {},
                    head = row.find('.tabh');

                // grabbing the numeric total for the row and assigning to values
                values.spend = row.find('.tdh').text();
                // each pie slice will now be styled in a CSS file -keeping style where it should be other than in JavaScript
                values.pieColour = row.find('th span').css('borderLeftColor');

                // increase total value
                totalSpend += parseInt(values.spend, 10);

                // push values into the array for access later
                pieData.push(values);

            }

            // iterate through each table row (only in the body)    
            $source.find('.tbh tr').each(prepare);



            // call the plugin to create the chart    
            var sizeman = 300
            var sizepiespace = sizeman /2
            var sizepie = sizeman / (30/13)
            if(pie){
            pie.clear();
            }
            pie = Raphael($container[0], sizeman, sizeman).renderPie(sizepiespace, sizepiespace, sizepie, pieData, totalSpend);

            // attaching an event to the Raphaël set that fades all the slice back to full opacity
            pie.mouseout(function() {
                pie.attr('opacity', 1);
            });

        };


// calling our makePie function on DOM ready
        function piefunc(){
         $(function() {
          dotNet.makePie($('table'),$('#pie'), pie);
    });
    }
   piefunc();

}

This is the checkbox that it applies to and where the pie is actually run.
            <form>
            <input type="checkbox" id="checker" onclick="checkFun();" />
            </form>

            <script type="text/javascript">



            var box = document.getElementById('checker');
        function checkFun(){
        allPie();

        }

    allPie();
    pieShower();
            </script>

When the checkbox is clicked it does generate a new pie with the desired effect, unfortunately it also pushes the previous version down and keeps it on the same page, and so as you keep checking and unchecking the box more and more are made on the page. Is there anyway to 'delete' or remove the chart that is already on the page while creating a new one with the desired effect?


Solution

  • try this

    make var pie a global variable instead local one

    and before the var pie = Raphael($container.....

    add the following

    if(pie){
        pie.clear();
    }
    

    also , your better use the graphael piechart api instead your current way (INMO)

    take a look at my jsfiddle with hover (glow like) effect + click callback