[Chartjs]-ChartJS Annotation Hide /Show

1👍

Another option is to update the chart by switching drawtime from “afterDatasetsDraw” to null, based on your desired condition.

Something like:

function toggleAnnotation(chart) {
    if (chart.options.annotation.drawTime == "afterDatasetsDraw"){
        chart.options.annotation.drawTime = null;
     } else {
        chart.options.annotation.drawTime = "afterDatasetsDraw";
     }
     chart.update();
}

0👍

I dont know if this is the best answer but since Chartjs Annotation Plugin doesn’t allow to show or hide annotations you can simple leave the annotation type blank and that will hide tha annotation.

then based on your condition you can add the type back again.

annotation: {

   drawTime: 'afterDatasetsDraw',
   annotations: [{
      id: 'hline1',
      type: '',
      mode: 'horizontal',
      scaleID: 'y-axis-0',
      value: 50,
      borderColor: 'red',
      borderDash: [8,5],
      borderWidth: 1,
      label: {
       backgroundColor: "red",
         content: "Benchmark",
         enabled: true,
          position : "left"
      }
   }, {
      id: 'hline2',
      type: '',
      mode: 'horizontal',
      scaleID: 'y-axis-0',
      value: 30,
      borderColor: 'green',
      borderDash: [8,5],
      borderWidth: 1,
      label: {
        backgroundColor: "green",
         content: "Target",
         enabled: true,
          position : "left"
      }
   }]

},

0👍

    function UnDraw() {
        window.myLine.config.data.datasets.forEach(function (dataset) {
            window.myLine.options.annotation.annotations.pop();
        });
        window.myLine.update();
    };
    function Draw(a) {
        window.myLine.options.annotation.annotations.push(
            {
                type: 'box',
                drawTime: 'afterDraw',
                xScaleID: 'x-axis-0',
                yScaleID: 'y-axis-0',
                xMax: a * 1000,
                xMin: a * 1000,
                yMax: MAXY,
                yMin: MINY,
                borderColor: 'rgba(255,102,0,1)',
                borderWidth: 1,
                backgroundColor: 'rgba(255,102,0,1)',
            });
        window.myLine.update();
    };

Leave a comment