[Chartjs]-Chart.js – Vertical crosshair (vertical annotation that moves with mouse) in line graph

4👍

This is the way I’ve done it: I’ve created an annotation whose value I change with an onmousemove event on the canvas.

var annotation = {
    annotations: [{
        type: 'line',
        mode: 'vertical',
        scaleID: 'x-axis',
        borderColor: '#b6fcd5',
        borderWidth: 2
    }]
};

var canvas = document.getElementById("chart");
var ctx = canvas.getContext("2d");

var myChart = new Chart(ctx,
    {
    ...
    },
        options: {
            tooltips: {
                mode: 'x',
                intersect: false
            },
            scales: {
                xAxes: [{
                    "id": 'x-axis',
                    type: 'time'
                }],
                ...
            },
            annotation: annotation
        }
    });

$(document).ready(function(){
    canvas.onmousemove = function (evt) {
        var points = myChart.getElementsAtXAxis(evt);
        annotation.annotations[0].value = new Date(myChart.config.data.labels[points[0]._index]);
        myChart.update();
    };
});

Leave a comment