Search code examples
javascripteventschart.js

Chart.js animation: onComplete event fired on hover


I am loading an image export of my chart after the animation is complete, using the onComplete callback. My problem is that everytime you hover over the diagram, the onComplete callback is executed an this slows down the page immensely.

Here's my chart code:

this.chart = new Chart(this.$chart.getContext("2d"), {
        type: 'doughnut',
        data: data,
        options: {
            tooltips: {
                enabled: false
            },
            animation: {
                onComplete: (e) => {
                    console.log(e);
                    this.initExport();
                }
            }
        }
    });

I checked the Chart.js documentation but I did not find any other option that would only fire after the chart is built. So does anyone know how to distinguish between the hover-animation and the "build"-animation of the chart?


Solution

  • Replace your animation option/object with the following :

    animation: {
       onComplete(e) => {
          this.options.animation.onComplete = null; //disable after first render
          console.log(e);
          this.initExport();
       }
    }
    

    Basically, you need to disable onComplete function by setting the chart.options.animation.onComplete property to null. This will make the onComplete function run only after the chart is rendered for the first time, and prevent it from firing when the chart gets hovered on.

    TIP : do not use arrow function for object­'s method. (this will always refer to the window object)