问题探讨 Link to heading

chart.js到LineChart图表默认动画方向是从下到上,没有像echart那样从左到右到效果。动画方向上写死到代码里面到,不可更改。我通过翻阅GitHub issues发现了有人提出过类似到问题,作者也简答了,可惜我能力有限没有理解作者到意思,那就从另一种思路开始解决吧。

issues

问题解决 Link to heading

我的思路是,把动画关闭也就是duration = 0,然后x轴数据固定,y轴数据通过update方法没次更新一个值,使用定时执行每50ms update一次,人眼就产生到从左到右到到感觉。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div>
    <img src="https://wong-1251253615.cos.ap-shanghai.myqcloud.com/blog/images/2019-03-13/chart.gif" alt="">
  </div>
  <div style="height: 300px;width: 500px">
    <canvas id="chart1"></canvas>
  </div>
  <script src="js/chart.js"></script>
  <script>
    var xData = ['x1','x2','x3','x4','x5','x6','x7','x8','x9','x10'],
        yData = [13,35,78,100,130,190,240,300,350,400],
        len = yData.length,
        count = 0;
    var myChart = new Chart('chart1',{
      type: 'line',
      data: {
        labels: xData,
        datasets:[{
          label: '测试', 
          backgroundColor: 'rgba(54, 162, 235, .8)', // 背景填充色
          borderColor: 'deepskyblue', // 路径颜色
          pointBackgroundColor: 'rgba(54, 162, 235, .4)', // 数据点颜色
          pointBorderColor: 'translate', // 数据点边框颜色
          data: [] // 对应的值
        }]
      },
      options: {
        animation: {
          duration: 0
        },
        scales: {
          yAxes:[{
            ticks:{
              max: 400
            }
          }]
        }
      }
    });
    var timer = setInterval(() => {
      if(count > len){
        clearInterval(timer)
      }
      myChart.data.datasets.forEach(function(dataset){
        dataset.data.push(yData[count])
      })
      myChart.update();
      count++;
    },100)
  </script>
</body>
</html>

gif