ChartJS注释隐藏/显示

问题描述 投票:2回答:2

我正在使用注释插件在我的图表中绘制水平线。有没有办法隐藏和显示基于条件的注释?

我的代码:

annotation: {

   drawTime: 'afterDatasetsDraw',
   annotations: [{
      id: 'hline1',
      type: 'line',
      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: 'line',
      mode: 'horizontal',
      scaleID: 'y-axis-0',
      value: 30,
      borderColor: 'green',
      borderDash: [8,5],
      borderWidth: 1,
      label: {
        backgroundColor: "green",
         content: "Target",
         enabled: true,
          position : "left"
      }
   }]

},
charts chart.js chart.js2
2个回答
0
投票

我不知道这是否是最好的答案,但由于Chartjs Annotation Plugin不允许显示或隐藏注释,您可以简单地将注释类型留空,这将隐藏注释。

然后根据您的情况,您可以再次添加类型。

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
投票

另一种选择是根据您所需的条件,通过将drawtime从“afterDatasetsDraw”切换为null来更新图表。

就像是:

function toggleAnnotation(chart) {
    if (chart.options.annotation.drawTime == "afterDatasetsDraw"){
        chart.options.annotation.drawTime = null;
     } else {
        chart.options.annotation.drawTime = "afterDatasetsDraw";
     }
     chart.update();
}
© www.soinside.com 2019 - 2024. All rights reserved.