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

如何在Chartist创建时实现柱状图的升起动画

实现Chartist.js柱状图的升起动画

嘿,我来帮你搞定Chartist.js的柱状图升起动画!其实它的animate核心是通过钩子函数控制柱子的样式过渡,下面我给你一套能实现“从底部升起”效果的完整方案,和你参考的示例效果一致:

1. 先准备基础HTML容器

<div class="ct-chart"></div>

2. 核心JS代码(带动画逻辑)

关键是利用animationBegin初始化柱子的初始状态,再通过draw回调让柱子过渡到目标形态:

// 图表数据,你可以替换成自己的内容
const chartData = {
  labels: ['周一', '周二', '周三', '周四', '周五'],
  series: [
    [5, 2, 4, 2, 6]
  ]
};

// 配置项重点:动画部分
const chartOptions = {
  animation: {
    duration: 1000, // 动画持续1秒
    easing: 'easeOutQuart', // 缓动函数,让动画结尾更自然
    // 动画开始前的钩子:把所有柱子先藏到底部
    animationBegin: function(chart) {
      chart.svg.querySelectorAll('.ct-bar').forEach(bar => {
        bar.style.height = '0'; // 初始高度为0
        bar.style.y = chart.chartRect.height(); // 定位到容器底部
      });
    },
    // 绘制阶段的动画回调:让柱子从初始状态过渡到目标状态
    draw: function(data) {
      return data.element.animate({
        // 高度从0涨到目标值
        height: {
          begin: 0,
          end: data.height
        },
        // Y轴位置从底部移到目标位置
        y: {
          begin: data.chartRect.height(),
          end: data.y
        }
      }, {
        duration: data.options.animation.duration,
        easing: data.options.animation.easing
      });
    }
  }
};

// 生成柱状图
new Chartist.Bar('.ct-chart', chartData, chartOptions);

3. 关键细节拆解

  • animationBegin钩子:动画启动前执行,先把所有柱子“压”到容器底部并设为0高度,这样动画开始时是从“无”到“有”的状态。
  • draw回调:这是动画的核心,data.element就是当前的柱子元素,我们通过animate定义它的height和y属性的过渡过程,从初始值(begin)平滑过渡到目标值(end)。
  • 缓动函数:easeOutQuart会让动画前期快、后期慢,比线性动画更贴合真实物理效果,你也可以换成easeInOutQuad等其他缓动函数试试。

4. 进阶:实现逐个升起的 stagger 动画

如果想要柱子逐个依次升起,只需要给每个柱子加个递增延迟就行:

draw: function(data) {
  // 每个柱子延迟150ms启动动画,index是柱子的顺序索引
  const delay = data.index * 150;
  return data.element.animate({
    height: { begin: 0, end: data.height },
    y: { begin: data.chartRect.height(), end: data.y }
  }, {
    duration: data.options.animation.duration,
    easing: data.options.animation.easing,
    delay: delay
  });
}

你可以根据需求调整动画时长、缓动函数或者延迟时间,试试就能看到和你参考示例一样的升起效果啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:30:18