Chart.js - 在线图

时间:2017-03-30 09:30:57

标签: momentjs chart.js

我正在使用Chart.js并且一直在寻找一种在我的图表中使用垂直注释/十字准线的方法。

当光标在图表中时,我希望此垂直线水平移动,跟随鼠标光标。

如何创建一个垂直十字准线,使用Chart.js根据光标移动改变其水平位置?

1 个答案:

答案 0 :(得分:2)

这就是我完成它的方式:我创建了一个注释,其值随着画布上的onmousemove事件而改变。

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();
    };
});
相关问题