ChartJs:如何仅禁用初始动画

qlvxas9a  于 2023-10-18  发布在  Chart.js
关注(0)|答案(2)|浏览(171)

我不喜欢图表JS线图的初始动画,但当我更新图形时,我确实想要一个动画。
我能找到的唯一相关解决方案,例如:
options: {animation: false}options: {animation: {duration: 0}}
禁用所有形式的动画。这不是我想要的
另一件我可以解决,但没有找到一种方法,是一种方法,切换动画回来后,当我更新图表。在初始化图表对象后,我似乎也找不到相关的值。因此,更改现有图表的动画似乎非常不符合艾德的要求。
我使用的是Chart.js 4.3.3。

uinbv5nw

uinbv5nw1#

您可以做的是在需要时手动启用动画。老实说,我不认为这是最好的解决办法,但它的工作

var ctx = document.getElementById('myCanva').getContext('2d');

var config = {
  type:'line',
  data:{
    labels:[0,1,2,3,4,5,6,7,8,9],
    datasets:[{
      data:[1,2,5,8,9,2,4,15,2,20],
      label:'A',
    }]
  },
  options:{
    animation:false,
    plugins:{
      zoom:{
        zoom:{
          drag:{
             enabled:true,
          },
          mode:'x',
        }
      }
    }
  }
} 

var myChart = new Chart(ctx, config);

function update3rdValue(){
  config.options.animation = true;
  config.data.datasets[0].data[2] = Math.floor(Math.random() * 20);
  myChart.update();
  config.options.animation = false;
}

function zoom(){
  config.options.animation = true;
  myChart.resetZoom();
  config.options.animation = false;
}

function zoomNoAnim(){
  myChart.resetZoom();
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js" integrity="sha512-UXumZrZNiOwnTcZSHLOfcTs0aos2MzBWHXOHOuB0J/R44QB0dwY5JgfbvljXcklVf65Gc4El6RjZ+lnwd2az2g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-zoom/2.0.1/chartjs-plugin-zoom.min.js" integrity="sha512-wUYbRPLV5zs6IqvWd88HIqZU/b8TBx+I8LEioQ/UC0t5EMCLApqhIAnUg7EsAzdbhhdgW07TqYDdH3QEXRcPOQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<canvas id="myCanva"></canvas>
<button onClick = "update3rdValue()">Edit 3rd value</button>
<button onClick = "zoom()">Reset Zoom</button>
<button onClick = "zoomNoAnim()">Reset Zoom without animation</button>
gudnpqoy

gudnpqoy2#

您可以使用自定义插件在使用自定义插件进行第一次渲染后启用动画:

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    animation: false
  },
  plugins: [{
    id: 'customAnimation',
    afterRender: (chart, args, opts) => {
      if (chart.options.animation !== false)
        return;

      chart.options.animation = true;
    }
  }]
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.3.3/chart.umd.js"></script>
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>

相关问题