[Chartjs]-Chart.js – How to set animation speed?

8πŸ‘

I love Chart.js, but this is definitely a part of the API that could stand to be improved for the sake of clarity.

Chart.js uses the window.requestAnimationFrame() method for animations, which is a more modern and efficient way to animate in the browser, since it only redraws on each screen refresh (i.e., based on the screen refresh rate, usually 60Hz). That prevents a lot of unnecessary calculations for frames that will never actually render.

At 60 frames/second, one frame lasts 16-2/3 milliseconds (1000ms / 60). Chart.js appears to round this off to 17ms, though. The API allows you to specify the number of steps globally, e.g.:

Chart.defaults.global.animationSteps = 60;

or just for the donut chart:

new Chart(ctx).Doughnut(data, {
  animationSteps: 60
});

Multiply 60 steps by 17ms/frame and your animation will run 1020ms, or just over one second. Since JavaScript programmers are used to thinking in milliseconds (not frames at 60Hz), to convert the other way, just divide by 17 to get the number of steps, e.g.:

Chart.defaults.global.animationSteps = Math.round(5000 / 17); // results in 294 steps for a 5-second animation

Hope that helps. I’m not sure what would cause those weird artifacts, though.

4πŸ‘

Use the animation object

options: {
        animation: {
            duration: 2000,
        },

I haven’t see this documented anywhere, but it’s incredibly helpful to not have to set the speed globally for every chart.

I also answered here

0πŸ‘

In case anyone comes across this question in the future (like I did), there is a new way of changing the animation duration. I guess this was an update to the Chart.js library at some point πŸ™‚

Chart.defaults.global.animation.duration = [ms];

So, for example, if you want a very fast 200ms animation, you can:

Chart.defaults.global.animation.duration = 200;

Hope this helps someone πŸ™‚

Leave a comment