Doesn't work with chart.js 2.7.x
nullpointer77 opened this issue · 6 comments
Samples do not work with chart.js 2.7.x
This seems to ultimately be a problem with the annotations plugin.
chartjs/chartjs-plugin-annotation#88
Please see my post on that issue to understand what I believe the root cause is. I was able to get around this problem by doing the following. .
static getChartById(chartId: string): any {
var foundChart = null;
Chart.helpers.each(Chart.instances,(instance) => {
if (chartId == instance.canvas.id) {
foundChart = instance;
return;
}
});
return foundChart;
}
var unFilteredCharJsInstance = ChartJsHelper.getChartById("UnfilteredChartFirst");
unFilteredCharJsInstance.options.annotation.annotations.pop();
unFilteredCharJsInstance.options.annotation.annotations.push({
type: 'line',
mode: 'vertical',
scaleID: 'x-axis-0',
value: point,
draggable: true,
borderColor: ConstantsService.constants['CprEditingLine'],
borderWidth: 3,
onDragEnd: function (event) {
let xaxis = unFilteredCharJsInstance.scales['x-axis-0'];
let x = event.x;
let epoch = xaxis.getValueForPixel(x);
//Below is a fix for chartjs-annotation and chartjs-dragable. Chart.js 2.7.x breaks these frameworks. This is a hack that may cause problems in the future.
this.value = epoch._i;
//THIS IS THE IMPORTANT BIT HERE
unFilteredCharJsInstance.options.annotation.annotations.pop();
unFilteredCharJsInstance.options.annotation.annotations.push(this);
unFilteredCharJsInstance.update(0);
}
});
The above seems to give the draggable plugin a working chart instance and dragging starts to work.
Please note that this shouldn't be considered a permanent fix, only a work around until the author of this plug is able to get a fix in place.
Quick update for those that care. I have likely tracked this bug to ChartJS. I have filed a bug/question to the chartjs team to see what direction they want to go. Please refer to this thread. chartjs/Chart.js#5111
Hi,
I got it working with Chart.js 2.9.3, you just have to add an id to the annotation, like so:
annotation: {
drawTime: "afterDraw",
events: ["click"],
annotations: [
{
id: "line1",
type: "line",
mode: "vertical",
scaleID: "x-axis-0",
value: 3,
borderColor: "red",
borderWidth: 2,
draggable: true,
onDragEnd: function() {
console.log(this.value);
}
}
]
}
Here's a working pen: https://codepen.io/juxtar/pen/jOEpWRB
Hey @juxtar,
does this pen still work for you? For me the annotation is not draggable.
Can you maybe tell me which browser you use?
Best,
Lukas
Yep, still works for me with Chrome 89.
Alright, thanks @juxtar!