Chartjs-Chartjs How to render a custom horizon line under X-Axis

0👍

You can capture the onclick event of the canvas and check which bar has been clicked with the getElementAtEvent method of chartjs. getElementAtEvent gives you all the relevant information you need (chart-width, x-coordinate of the bar, label etc.) to draw a custom line below the chart.

    canvas.onclick = function (evt) {
        var activePoints = myBarChart.getElementAtEvent(evt);
        if (activePoints[0]) {
            //draw your custom line 
        }
     };

The snippet below has two canvas. One for chart.js to draw the actual chart and the second below to draw a line with the text of the clicked label.

var canvas = document.getElementById('myChart');
var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
        label: "My First dataset",
        backgroundColor: "rgba(255,99,132,0.2)",
        borderColor: "rgba(255,99,132,1)",
        borderWidth: 2,
        hoverBackgroundColor: "rgba(255,99,132,0.4)",
        hoverBorderColor: "rgba(255,99,132,1)",
        data: [65, 59, 20, 81, 56, 55, 40],
    }]
};
var option = {
    scales: {
        yAxes: [{
            stacked: true,
            gridLines: {
                display: true,
                color: "rgba(255,99,132,0.2)"
            }
        }],
        xAxes: [{
            gridLines: {
                display: false
            }
        }]
    }
};

var myBarChart = Chart.Bar(canvas, {
    data: data,
    options: option
});

canvas.onclick = function (evt) {
    var activePoints = myBarChart.getElementAtEvent(evt);
    if (activePoints[0]) {
        var chart = activePoints[0]._chart;
        var canvasX = document.getElementById('xAxis2');
        // set the width of the second canvas to the chart width
        canvasX.width = chart.width;
        var canvas2D = canvasX.getContext('2d');
        // draw the line
        canvas2D.moveTo(0, 20);
        canvas2D.lineTo(activePoints[0]._view.x - 10, 20);
        canvas2D.lineTo(activePoints[0]._view.x, 0);
        canvas2D.lineTo(activePoints[0]._view.x + 10, 20);
        canvas2D.lineTo(canvasX.width, 20);
        canvas2D.stroke();
        // add the label text
        canvas2D.font = '12px serif';
        canvas2D.fillText('for ' + activePoints[0]._view.label, canvasX.width - 100, 15);
    }
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<canvas id="myChart" width="400" height="250"></canvas>
<canvas id="xAxis2" height="20"></canvas>

Leave a comment