Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the Chart.js animate when scrolled to that section?

I am trying to use the pie chart from Chart.js (http://www.chartjs.org/docs/#pieChart-exampleUsage). Everything works smooth, but the animation happens as soon as the page loads, but since the user has to scroll down to see the chart, they won't see the animation. Is there anyway I can make the animation to start only when scrolled to that position? Also if possible, is it possible to animate everytime when that chart becomes into view?

My code is as follows:

<canvas id="canvas" height="450" width="450"></canvas>
    <script>
        var pieData = [
                {
                    value: 30,
                    color:"#F38630"
                },
                {
                    value : 50,
                    color : "#E0E4CC"
                },
                {
                    value : 100,
                    color : "#69D2E7"
                }

            ];

    var myPie = new Chart(document.getElementById("canvas").getContext("2d")).Pie(pieData);

    </script>
like image 724
Suthan Bala Avatar asked Sep 12 '13 19:09

Suthan Bala


2 Answers

You can combine the check for whether something is viewable with a flag to keep track of whether the graph has been drawn since it appeared in the viewport (though doing this with the plugin bitiou posted would be simpler):

http://jsfiddle.net/TSmDV/

var inView = false;

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemTop <= docViewBottom) && (elemBottom >= docViewTop));
}

$(window).scroll(function() {
    if (isScrolledIntoView('#canvas')) {
        if (inView) { return; }
        inView = true;
        new Chart(document.getElementById("canvas").getContext("2d")).Pie(data);
    } else {
        inView = false;  
    }
});
like image 59
Jason P Avatar answered Oct 24 '22 06:10

Jason P


Best to use deferred plugin

https://chartjs-plugin-deferred.netlify.com/

<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-deferred@1"></script>

new Chart(ctx, {
  // ... data ...
  options: {
    // ... other options ...
    plugins: {
      deferred: {
        xOffset: 150,   // defer until 150px of the canvas width are inside the viewport
        yOffset: '50%', // defer until 50% of the canvas height are inside the viewport
        delay: 500      // delay of 500 ms after the canvas is considered inside the viewport
      }
    }
  }
});
like image 3
sierra.charli3 Avatar answered Oct 24 '22 05:10

sierra.charli3