[Chartjs]-ChartsJS Annotations Plugin โ€“ Can you create a tooltip to accompany an annotation?

0๐Ÿ‘

Not directly answering your question, but you can modify the chart and annotations in any way you prefer (in ChartJS v3) by accessing the context chart and element (docs)

I used this to change style of annotation on hover (in TypeScript):

enter: (context) => {
    const id = context.element.options.id!;
    ((context.chart.options.plugins!.annotation!.annotations as any)[id] as AnnotationOptions).borderColor = 'blue';
    context.chart.canvas.style.cursor = 'pointer';
    context.chart.update();
},
leave: (context) => {
    const id = context.element.options.id!;
    ((context.chart.options.plugins!.annotation!.annotations as any)[id] as AnnotationOptions).borderColor = 'rgb(255, 99, 132)';
    context.chart.canvas.style.cursor = 'default';
    context.chart.update();
},

0๐Ÿ‘

You can use a label for the annotation whose display is changed when the mouse enters and leaves (see Events configuration).

annotation: {
    annotations: [{
        type: 'line',
        borderWidth: 2,
        xMin: someX,
        xMax: someX, // xMin = xMax for vertical line
        label: {
            display: false,
            backgroundColor: 'green',
            drawTime: 'afterDatasetsDraw',
            content: 'Some content for tooltip'
        },
        enter({ element }, event) {
            element.label.options.display = true;
            return true; // force update
        },
        leave({ element }, event) {
            element.label.options.display = false;
            return true;
        }
    }]
}

See the Label visibility example in the chartjs-plugin-annotation documentation.

Leave a comment