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

查看:1030
本文介绍了如何使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天全站免登陆