Chartjs-Chart.js the value on the graph does not disappear when deselected

0👍

This is mainly because the animation.oncomplete event is called again when the legend is filtered.

You need to have an extra check like this dataset._meta[0].$filler.visible != false to only show values for only visible datasets.

Below is corrected code or fiddle for your reference -> https://jsfiddle.net/x164L2z9/

var ctx = document.getElementById("canvas").getContext("2d");
var nomi = [2017, 2018, 2019];

var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: nomi,
    datasets: [{
        label: 'PP PERVENUTI',
        data: [50, 30, 45],
        backgroundColor: "#8A0808",
        fill: false,
        borderColor: "#8A0808",
        borderWidth: 3
      },
      {
        label: 'PP EVASI',
        data: [60, 45, 12],
        backgroundColor: "#0B610B",
        fill: false,
        borderColor: "#0B610B",
        borderWidth: 3
      },
      {
        label: 'PI PERVENUTI',
        data: [20, 25, 35],
        backgroundColor: "#8A0886",
        fill: false,
        borderColor: "#8A0886",
        borderWidth: 3
      },
      {
        label: 'PI EVASI',
        data: [10, 20, 30],
        backgroundColor: "#0404B4",
        fill: false,
        borderColor: "#0404B4",
        borderWidth: 3
      }
    ]
  },
  options: {
    legend: {
      display: true,
      position: "bottom"
    },
    hover: {
      animationDuration: 0
    },
    animation: {
      onComplete: function() {

        var ctx = this.chart.ctx;
        ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
        ctx.fillStyle = "black";
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';

        this.data.datasets.forEach(function(dataset) {
          if (dataset._meta[0].$filler.visible != false) {
            for (var i = 0; i < dataset.data.length; i++) {
              for (var key in dataset._meta) {
                var model = dataset._meta[key].data[i]._model;
                ctx.fillText(dataset.data[i], model.x, model.y - 5);
              }
            }
          }

        });
      }
    }

  }
});

Leave a comment