JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div class="blankDiv">
Scroll Down to See the chart
</div>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
<div id="chartContainer1" style="height: 300px; width: 100%;"></div>
<div id="chartContainer2" style="height: 300px; width: 100%;"></div>
CSS
.blankDiv {
height: 1000px;
width: 100%;
}
JavaScript
window.onload = function () {
var options = {
title:{
text: "Animate Chart on Scroll"
},
animationEnabled: true,
data: [
{
// Change type to "doughnut", "line", "splineArea", etc.
type: "column",
dataPoints: [
{ label: "apple", y: 10 },
{ label: "orange", y: 15 },
{ label: "banana", y: 25 },
{ label: "mango", y: 30 },
{ label: "grape", y: 28 }
]
}
]
};
var chart = [];
var offsetForChartToDisplay = [];
var chartAnimated = [];
chart.push(new CanvasJS.Chart("chartContainer", options));
chart.push(new CanvasJS.Chart("chartContainer1", options));
chart.push(new CanvasJS.Chart("chartContainer2", options));
for(var i=0; i<chart.length; i++) {
offsetForChartToDisplay.push(chart[i].container.offsetTop + 150);
}
function scrollFunction() {
var currentScrollPos = document.documentElement.scrollTop+window.innerHeight;
for(var i=0; i<chart.length; i++) {
if( currentScrollPos > offsetForChartToDisplay[i]) {
//remove the event listener once all charts has been rendered
if(chartAnimated.length == 3) {
window.removeEventListener("scroll", scrollFunction);
break;
}
//once the chart is animated, don't call render method again
if(chartAnimated.indexOf(i) == -1) {
chart[i].render();
chartAnimated.push(i);
}
}
}
}
window.addEventListener("scroll", scrollFunction);
}