Chart.js - How to set animation speed?

梦想与她 提交于 2020-03-01 04:21:49

问题


I'm using Chart.js (documentation), but there doesn't seem to be an option to set the animation speed.

I can't even seem to find an animation speed / time variable in the source code.

How do I go about doing this?

(ps: I'm using Doughnut charts)

EDIT: Changing animationSteps, shows weird artefacts after the animation is complete, for several values (ie: 30 or 75). 60 is working fine. And it doesn't only appear with 100+ values of the chart:


回答1:


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.




回答2:


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




回答3:


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 :-)



来源:https://stackoverflow.com/questions/19837523/chart-js-how-to-set-animation-speed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!