# 动画

  • 加载动画
  • 增量动画
  • 动画的配置

# 1. 加载动画

说明:

  • loading 动画
  • echarts 有内置的加载动画,直接控制其 显示或隐藏 即可

实现:

const myChart = echarts.init(boxElement);

myChart.showLoading();

myChart.hideLoading();

示例:

<!--39-animation-loading.html-->
<div id="box_39-animation-loading" style="width: 400px; height: 400px;"></div>
<script type="module">
  const myChart = echarts.init(document.querySelector('#box_39-animation-loading'));
  myChart.showLoading();
  setTimeout(() => myChart.hideLoading(), 3000);
</script>

# 2. 增量动画

说明:

  • option 变化后, echarts 会自动使用合适的过渡动画
  • 通过 myCharts.setOption(option) 实现
  • 设置新的 option 会合并到旧 option

示例:

<!--40-animation-increment.html-->
<div id="box_40-animation-increment" style="width: 600px; height: 400px;"></div>
<script type="module">
  const myChart = echarts.init(document.querySelector('#box_40-animation-increment'));
  myChart.setOption({
    dataset: {
      dimensions: ['name', 'math'],
      source: [],
    },
    yAxis: { type: 'category'},
    xAxis: { type: 'value'},
    series: [
      { name: '语文', type: 'bar', label: {show: true}, barWidth: '30%',
        encode: { y: 'name', x: 'math'}
      },
    ]
  });
  let source = [
    { name: '张三', math: 90 }, { name: '李四', math: 80 },
    { name: '王五', math: 70 }, { name: '赵六', math: 60 },
  ];
  setInterval(() => {
    source = source.map(({name, math}) => ({ name, math: math + Math.floor(Math.random() * 10) }));
    myChart.setOption({ dataset: { source } })
  }, 1000);
</script>

# 3. 动画配置

# 3.1. 开启动画

option = {
  animation: true, // 默认开启
}

# 3.2. 动画时长

option = {
  // 值 可以是毫秒数,也可以是回调
  // 每种类别的 idx 都是从 0 开始
  // 柱状图中,所有的柱子是一个类别,markLine 是一个类别,MarkPoint 也是一个类别
  animationDuration: function (idx) {
    // 越往后的数据时长越大
    return idx * 100;
  }
}

# 3.3. 缓动效果

option = {
  animationEasing: 'cubicOut'
}

参考: https://echarts.apache.org/examples/zh/editor.html?c=line-easing

# 3.4. 动画的阈值

是否开启动画的阈值,当单个系列显示的图形数量大于这个阈值时会关闭动画。

比如说,柱状图,有 8 个柱子,如果 animationThreshold = 7 则不会有动画

option = {
  animationThreshold: 2000,
}
本章目录