Animate Chart.JS Only Once

橙三吉。 提交于 2019-12-24 14:47:31

问题


I've delayed animation of a Chart.js canvas until it's brought into the viewport, but am struggling to limit this to only one animation. I'd greatly appreciate any input on this.

Here's the code:

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('#trigger')) {
        if (inView) { return; }
        inView = true;
        new Chart(document.getElementById("myChart").getContext("2d")).Line(data, {
            responsive: true,
            maintainAspectRation: true,
            animationSteps: 175,
            showScale: false,
            scaleShowGridLines : false,
            scaleShowLabels: false,
            showTooltips: false
       });
    } else {
        inView = false;  
    }
});

回答1:


You need to keep track of whether the chart was already generated. The trigger element is one place you can do this (if you are not using the same trigger for multiple charts), otherwise you could use the canvas element as well.

You also don't need inView

...
if (isScrolledIntoView('#trigger')) {
    if ($('#trigger').data("generated")) { return; }
    $('#trigger').data("generated", true);
    ...


来源:https://stackoverflow.com/questions/33356826/animate-chart-js-only-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!