【发布时间】:2021-01-25 14:18:07
【问题描述】:
我尝试在 Chart.js 中动态设置 animation。它应该根据某些条件启用或禁用。
但由于某种原因,它总是被启用或禁用。
我创建了一个JSFiddle 来更好地描述我的问题
查看下面的代码:
<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", "Blue", "Yellow", "Green", "Purple", "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
}
【问题讨论】:
标签: javascript chart.js chart.js2