简体   繁体   中英

Animate Chart.JS Only Once

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM