You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Chart.js图表实现页面加载时的平滑动画效果?

实现Chart.js柱状图的平滑加载动画

我看你目前的代码里把animation.duration设成了10毫秒——这就是图表瞬间完全显示、看不到动画效果的核心原因。要实现页面加载时柱状图平滑升起的视觉效果,只需要调整Chart.js的动画配置项,给动画足够的时长,再搭配合适的缓动函数就可以了。

核心修改要点

  • 增大animation.duration的值:比如设置为1500(对应1.5秒),数值越大动画速度越慢,你可以根据需求灵活调整
  • 可选添加animation.easing:用'easeOutQuart'这类平滑的缓动函数,让动画的收尾更自然流畅
  • 确保动画功能处于启用状态(你的代码已经开启了animation,只是时长设置得太短)

修改后的完整代码

<script>
var department = {{department|safe}};
var incomplete = {{incomplete|safe}};
var complete = {{complete|safe}};

// Return with commas in between
var numberWithCommas = function (x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

var bar_ctx = document.getElementById('bar-chart');
var bar_chart = new Chart(bar_ctx, {
    type: 'bar',
    data: {
        labels: department,
        datasets: [
            {
                label: 'incomplete',
                data: incomplete,
                backgroundColor: "rgba(55, 160, 225, 0.7)",
                hoverBackgroundColor: "rgba(55, 160, 225, 0.7)",
                hoverBorderWidth: 2,
                hoverBorderColor: 'lightgrey'
            },
            {
                label: 'complete',
                data: complete,
                backgroundColor: "rgba(225, 58, 55, 0.7)",
                hoverBackgroundColor: "rgba(225, 58, 55, 0.7)",
                hoverBorderWidth: 2,
                hoverBorderColor: 'lightgrey'
            },
        ]
    },
    options: {
        animation: {
            duration: 1500, // 调整为1.5秒,可按需修改时长
            easing: 'easeOutQuart' // 平滑缓动函数,提升动画质感
        },
        tooltips: {
            mode: 'label',
            callbacks: {
                label: function (tooltipItem, data) {
                    return data.datasets[tooltipItem.datasetIndex].label + ": " + numberWithCommas(tooltipItem.yLabel);
                }
            }
        },
        scales: {
            xAxes: [{
                stacked: true,
                gridLines: {
                    display: false
                },
            }],
            yAxes: [{
                stacked: true,
                ticks: {
                    callback: function (value) {
                        return numberWithCommas(value);
                    },
                },
            }],
        },
        legend: {
            display: true
        }
    }
});
</script>

进阶个性化动画(可选)

如果想让柱子依次逐个动画,而不是同步升起,可以给animation添加delay回调:

animation: {
    duration: 1500,
    easing: 'easeOutQuart',
    delay: function(context) {
        // 索引越大的柱子延迟越长,实现依次动画效果
        return context.dataIndex * 100;
    }
}

Chart.js还支持linear、easeInOutQuad等多种缓动函数,你可以根据喜好选择适配的动画曲线。

内容的提问来源于stack exchange,提问作者davidjbeiler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:27:56