在鼠标悬停Chart.JS上显示点数据

时间:2018-10-16 11:46:07

标签: javascript html chart.js mouseevent mousehover

当我将鼠标悬停在图表上时,我想在图表上获取当前位置的数据(x / y轴数据)。下面的代码可以很好地工作,例如,当for循环设置为1倍时(图表是静态的并且不移动时),但是当我将for循环设置为更高的数字时(因此图表不会是静态的,它会移动),而它在移动时,数据框已损坏并且无法很好地显示我所在的轴数据。

这是我的html代码:

<!DOCTYPE html>
<html>
<head>
    <script src="jquery.js"></script>
    <script src = "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
    <script src="client.js"></script>
</head>
<body>
    <button>click me to alert lmao</button>
    <div class="container">
        <canvas id="line-chart" width="800" height="450"></canvas>
    </div>
</body>
</html>

这是我的JavaScript代码:

$(document).ready(function(){
    var myChart = document.getElementById('line-chart').getContext('2d');
    var foo = new Array(10);
    for(var i=0;i<foo.length;i++){
        foo[i] = i+1;
    }
    var chart = new Chart(document.getElementById("line-chart"), {
        type: 'line',
        data: {
            labels: foo,
            datasets: [{
                data: [],
                label: "try1",
                borderColor: "#ff0000",
                fill: false
            }
            ]
        },
        options: {
            tooltips: {
                mode: 'index',
                intersect: false
            },
            hover: {
                mode: 'index',
                intersect: false
            },
            elements: {
                point:{
                    radius: 0
                }
            }
        }   
    });
    $("button").click(function(){
        for(var i = 0; i < 1000; i++)
        {
            call();
        }    
    });
    var arr1 = [1,2,3,4,5,6,7,8,9,10]
    var arr2 = [10,9,8,7,6,5,4,3,2,1]
    function  aarr1() {
        $.ajax({

            complete: function(data){
                var chartData = chart.data;
                chartData.datasets[0].data = arr1;
                chart.update();
            }
        });

    }
    function  aarr2() {
        $.ajax({
            complete: function(data){
                var chartData = chart.data;
                chartData.datasets[0].data = arr2;
                chart.update();
            }
        });

    }
    function call(){
        aarr1();
        aarr2();
    }
});

0 个答案:

没有答案