在 Chart.JS 中动态设置动画

问题描述

我尝试在 Chart.js 中动态设置 animation。它应该根据某些条件启用或禁用。

但它总是出于某种原因被启用或禁用。

我做了一个JSFiddle来更好地描述我的问题

enter image description here

查看下面的代码

<div class="container">

   <button onclick="chart(true)">ANIMATION</button>

   <button onclick="chart(false)">NO ANIMATION</button>
    
   <div id="animation-info"></div>
 
   <canvas id="chart-container" width="300" height="200"></canvas>

</div>
let animation = true
let CHART

chart(animation)


function chart(animation) {

  const anim_duration = animation == false 
  ? { duration : 0 }
  : { duration : 1000 }
  
  document.getElementById('animation-info').innerHTML =  `<br>Animation: ${animation} <br> Animation duration: ${anim_duration.duration}`

  
  // generate dataset with random values
  // random values are actual chart values here
  var dataset = Array.from( { length: 6 },() => Math.floor(Math.random() * 6 + 1 ))
  
  var options = {
    type: 'doughnut',data: {
      labels: ["Red","Blue","Yellow","Green","Purple","Orange"],datasets: [{
          label: '# of Votes',data: dataset,backgroundColor: [ "Red","Orange" ],borderWidth: 1,}
      ]
    },options: {
       animation: anim_duration,cutoutPercentage : 60,responsive: true,}
  }
  
  var ctx = document.getElementById('chart-container').getContext('2d')


  if (typeof CHART == "undefined")
        CHART = new Chart(ctx,options)

  else {
        CHART.config = options  // updating with new chart data
        CHART.update()               // redraw the chart
  }
}
.container {
  text-align: center;
  padding: 20px;
}

#animation-info {
  padding: 5px;
  font-size: 16px;
  font-family: Arial;
}

canvas { 
  opacity : 0.7; 
  margin-top: 20px;
}

button {
  padding: 10px 20px;
  margin: 10px;
}

我也试过直接设置选项

Chart.defaults.global.animation.duration = duration

似乎是同样的问题。


我认为问题是因为我不是每次都调用 new Chart(ctx,options),而是只更新图表配置数据。

我这样做是为了节省资源,因为我多次重建图表并且每次调用 new Chart(ctx,options) 似乎都是一个相当繁重的操作。


解决方案:

正如 LeeLenalee 在他下面的评论中建议的那样添加

CHART.options.animation.duration = animation == false ?  0 : 1000` 

CHART.update()之前做了个伎俩

if (typeof CHART == "undefined")
    CHART = new Chart(ctx,options)

else {
     CHART.config = options  // updating with new chart data
     CHART.options.animation.duration = animation == false ? 0 : 1000
     CHART.update()               // redraw the chart
}

解决方法

您试图将选项设置错误。两个版本都有效。如果您想将其设置为默认值,则必须像这样:Chart.defaults.global.animation.duration = animation ? 1000 : 0。你也可以像这样把它放在你的选项对象中:

const anim_duration = { duration : animation ? 1000 : 0 }

options: {
  animation: anim_duration
}

小提琴:https://jsfiddle.net/Leelenaleee/58pxb1j2/9/

评论澄清后编辑: 在更新方法 CHART.options.animation.duration = animation ? 1000 : 0; 中设置动画,然后调用更新。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...