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