[英]How to make the Chart.js animate when scrolled to that section?
我正在尝试使用 Chart.js ( http://www.chartjs.org/docs/#pieChart-exampleUsage ) 中的饼图。 一切都很顺利,但动画会在页面加载后立即发生,但由于用户必须向下滚动才能看到图表,因此他们不会看到动画。 无论如何,我可以让动画仅在滚动到该位置时开始吗? 此外,如果可能的话,是否可以在每次看到该图表时进行动画处理?
我的代码如下:
<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 执行此操作会更简单):
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;
}
});
最好使用延迟插件
https://chartjs-plugin-deferred.netlify.com/
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-deferred@1"></script>
new Chart(ctx, {
// ... data ...
options: {
// ... other options ...
plugins: {
deferred: {
xOffset: 150, // defer until 150px of the canvas width are inside the viewport
yOffset: '50%', // defer until 50% of the canvas height are inside the viewport
delay: 500 // delay of 500 ms after the canvas is considered inside the viewport
}
}
}
});
我不知道您是否可以这样做,我遇到了同样的问题并以这种简单的方式在没有任何插件的情况下解决了它,请查看:
$(window).bind("scroll", function(){
$('.chartClass').each(function(i){
var dougData = [
{value: 100, color:"#6abd79"},
{value: 20, color:"#e6e6e6"}
];
var graphic = new Chart(document.getElementById("html-charts").getContext("2d")).Doughnut(dougData, options);
$(window).unbind(i);
});
});
我在 Chart.js 上遇到了同样的问题,并找到了一个非常好的解决方案。 GitHub 上有一个被FVANCOP称为ChartNew.js的包。 他扩展了它并添加了几个功能。
查看示例,图表是通过向下滚动绘制的。
负责的是声明
dynamicDisplay : true
使用IntersectionObserver是更现代的方法,它使您能够选择在触发事件之前必须有多少元素可见。
阈值为 0 意味着它会在元素的任何部分可见时触发,而阈值为 1 意味着整个元素必须可见。
它比听滚动效果更好,并且只会在元素从隐藏转换为可见时触发一次,即使在您连续滚动时也是如此。 如果页面内容因其他事件而更改,例如其他内容被隐藏/显示或窗口大小调整等,它也适用。
这就是我制作径向图表的方式,每次至少有 20% 出现在视图中时都会进行动画处理:
const options = {
series: [75],
chart: {
type: 'radialBar',
},
};
const chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
const observer = new IntersectionObserver(function(entries) {
if (entries[0].isIntersecting === true) {
chart.updateSeries([0], false); // reset data to 0, then
chart.updateSeries([75], true); // set original data and animate
// you can disconnect the observer if you only want this to animate once
// observer.disconnect();
}
}, { threshold: [0.2] });
observer.observe(document.querySelector("#chart"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.