[Chartjs]-Chart.js doughnut animate/draw clockwise

3👍

Reverse the data sorting

This is not an answer specifically on how to animate the ChartJs anti-clockwise, but i think it’ll solve your problem.

I had an issue where I wanted to show one Bar chart and one Pie chart with the same data, and the Bar chart had to be sorted by number (greater to smaller). This is what I got, firstly:

First attempt

But, as you can see, because the Pie chart is animated clockwised, the ‘order’ of the data differs from the Bar chart to the Pie chart. In the Bar chart, I had Blue, Red and Yellow, and in the Pie chart, visually speaking, I had Yellow, Red and Blue.

What I did was, after generating the Bar chart, reversing the labels, data and colors arrays. See:

var backgroundColors = [bgColor1, bgColor2, ...];
var borderColors = [bdColor1, bdColor2, ...];

dataArrayReversed = dataArray.reverse();
labelsArrayReversed = labelsArray.reverse();
backgroundColorsReversed = backgroundColors.slice(0, dataArray.length).reverse();
borderColorsReversed = borderColors.slice(0, dataArray.length).reverse();

Also, you’ll need to reverse the legend order in the chart declaration, so it stays ordered:

 var pieChart = new Chart(ctxPie, {
                        type: 'pie',
                        data: {
                             labels: labelsArrayReversed,
                             datasets: [
                                  data: dataArrayReversed,
                                  backgroundColor: backgroundColorsReversed,
                                  borderColors: borderColorsReversed,
                                  borderWidth: 2
                             ]
                        },
                        options: {
                            legend: { reverse: true }
                        }
                    });

Yay!

The animation is clockwise, but the visual effect is correct.

It’s the same for doughnut charts.

Leave a comment