滚动到该部分时如何使 Chart.js 动画化? [英] How to make the Chart.js animate when scrolled to that section?

查看:15
本文介绍了滚动到该部分时如何使 Chart.js 动画化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Chart.js (http://www.chartjs.org/docs/#pieChart-exampleUsage).一切都很顺利,但动画会在页面加载后立即发生,但由于用户必须向下滚动才能看到图表,因此他们不会看到动画.无论如何,我可以让动画仅在滚动到该位置时开始吗?另外,如果可能的话,是否可以在每次看到该图表时都进行动画处理?

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?

我的代码如下:

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

推荐答案

您可以将检查某物是否可见的检查与一个标志相结合,以跟踪自图形出现在视口中以来是否已绘制该图形(尽管这样做发布插件 bitiou 会更简单):

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;  
    }
});

这篇关于滚动到该部分时如何使 Chart.js 动画化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆