我正在使用注释插件来绘制图表中的水平线。有什么方法可以隐藏&根据条件显示注释?
我的代码:
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"
}
}]
},
另一个选项是根据您所需的条件将绘图时间从" afterdatasetsdraw"切换到null。
。类似:
function toggleAnnotation(chart) {
if (chart.options.annotation.drawTime == "afterDatasetsDraw"){
chart.options.annotation.drawTime = null;
} else {
chart.options.annotation.drawTime = "afterDatasetsDraw";
}
chart.update();
}
我不知道这是否是最好的答案,但是由于ChartJS注释插件不允许显示或隐藏注释,因此您可以简单地将注释类型放置为空白,并且会隐藏tha notation。/p>
然后,根据您的条件,您可以再次添加类型。
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"
}
}]
},
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();
};