javascript – 如何使用Chart.js将点击事件添加到我的折线图

前端之家收集整理的这篇文章主要介绍了javascript – 如何使用Chart.js将点击事件添加到我的折线图前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图使用 Chart.js将点击事件添加到我的折线图中.我已经启用了我的工具提示,以显示我的折线图中的信息,但我也想添加一个点击方式,让我知道用户点击x轴.现在我只想弹出一个警报,给我在用户点击的x轴上的值.

研究:

我看过@L_404_1@,我发现这个方法:.getPointsAtEvent(event)

Calling getPointsAtEvent(event) on your Chart instance passing an
argument of an event,or jQuery event,will return the point elements
that are at that the same position of that event.

canvas.onclick = function(evt){
    var activePoints = myLineChart.getPointsAtEvent(evt);
    // => activePoints is an array of points on the canvas that are at the same position as the click event. };

我不知道如何使用或在哪里将函数放在我的代码中.如果有人可以帮助我找出可以添加到我的代码的地方,那将是非常感谢!

我的代码:(在javascript中)

//NOTE: the div 'roomForChart' has been already declared as <div id="roomForChart"></div>


 //creating html code inside of javascript to display the canvas used for the graph
 htmlForGraph = "<canvas id='myChart' width ='500' height='400'>";
 document.getElementById('roomForChart').innerHTML += htmlForGraph;

 //NOW TO CREATE DATA

   //the data for my line chart
    var data = {
         labels: ["Aug 1","Aug 2","Aug 3","Aug 4","Aug 5"],//the x axis
          datasets: [
            {   //my red line
                label: "Usage Plan",fillColor: "rgba(255,255,0.2)",//adds the color below the line
                strokeColor: "rgba(224,1)",//creates the line
                pointColor: "rgba(244,pointStrokeColor: "#fff",pointHighlightFill: "#fff",pointHighlightStroke: "rgba(220,220,data: [1024,1024,1024]
           },{    //my green line
            label: "Overall Usage",fillColor: "rgba(48,197,83,strokeColor: "rgba(48,pointColor: "rgba(48,pointHighlightStroke: "rgba(48,data: [15,25,45,1500]
       },{  //my blue line
            label: "Daily Usage",fillColor: "rgba(151,187,205,strokeColor: "rgba(151,pointColor: "rgba(151,pointHighlightStroke: "rgba(151,10,20,5]
       }

     ] //ending the datasets
     }; //ending data


    //creating a variable for my chart
    var ctx = document.getElementById("myChart").getContext("2d");




//code to create a maximum y value on the chart
var maxUsage = 1024;
var maxSteps = 5;
var myLineChart = new Chart(ctx).Line(data,{
    pointDot: false,scaleOverride: true,scaleSteps: maxSteps,scaleStepWidth: Math.ceil(maxUsage / maxSteps),scaleStartValue: 0

});

 //what I have tried but it doesn't show an alert message
ctx.onclick = function(evt){
    var activePoints = myLineChart.getPointsAtEvent(evt);
    // => activePoints is an array of points on the canvas that are at the same position as the click event.
   alert("See me?");
};

对于那些在这里很难看到图表的人,你去:

希望我提供足够的信息来获得一些帮助.如果我需要自己解释,请让我知道.先谢谢你!!! 原文链接:https://www.f2er.com/js/152090.html

猜你在找的JavaScript相关文章