如何使用Chart.js将单击事件添加到我的折线图中

Mad*_*ess 13 javascript charts linechart onclick chart.js

我正在尝试使用Chart.js将单击事件添加到我的折线图中.我已经启用了我的工具提示以显示来自折线图的信息,但我还想添加一个点击方法,让我知道用户点击x轴的位置.现在我只想弹出警报,给我用户点击的x轴上的值.

研究:

我查看了Chart.js文档,我遇到了这个方法:.getPointsAtEvent(event)

在Chart实例上调用getPointsAtEvent(event)传递事件或jQuery事件的参数将返回该事件的相同位置的点元素.

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. };
Run Code Online (Sandbox Code Playgroud)

我只是无法弄清楚如何使用或在我的代码中将函数放在何处.如果有人可以帮我弄清楚我可以将其添加到我的代码中,我们将不胜感激!

我的代码:(在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,255,0.2)", //adds the color below the line
                strokeColor: "rgba(224,0,0,1)",//creates the line
                pointColor: "rgba(244,0,0,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [1024, 1024, 1024, 1024, 1024]
           },

       {    //my green line
            label: "Overall Usage",
            fillColor: "rgba(48,197,83,0.2)",
            strokeColor: "rgba(48,197,83,1)",
            pointColor: "rgba(48,197,83,1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(48,197,83,1)",
            data: [15, 25, 45, 45, 1500]
       },
        {  //my blue line
            label: "Daily Usage",
            fillColor: "rgba(151,187,205,0.2)",
            strokeColor: "rgba(151,187,205,1)",
            pointColor: "rgba(151,187,205,1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(151,187,205,1)",
            data: [15, 10, 20, 0, 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?");
};
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

希望我提供了足够的信息来获得一些帮助.如果我需要解释自己,请告诉我.先感谢您!!!:)

hex*_*D49 7

改变这一行

document.getElementById('roomForChart').innerHTML += htmlForGraph;
Run Code Online (Sandbox Code Playgroud)

对此

holder = document.getElementById('roomForChart');
holder.innerHTML += htmlForGraph;
Run Code Online (Sandbox Code Playgroud)

进一步你会有你的片段,修改了一下

holder.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?");
};
Run Code Online (Sandbox Code Playgroud)

console.log(activePoints);在onclick处理程序中添加以查看activePoints变量的内容.我可以看到,有三个对象.例如,这些是值activePoints[0]

datasetLabel: "Usage Plan"
fillColor: "rgba(244,0,0,1)"
highlightFill: "#fff"
highlightStroke: "rgba(220,220,220,1)"
label: "Aug 4"
strokeColor: "#fff"
value: 1024
x: 371
y: 12.356097560975627
Run Code Online (Sandbox Code Playgroud)

他们可以按如下方式访问

activePoints[0].label
activePoints[0].x
activePoints[0].y
activePoints[0].value
Run Code Online (Sandbox Code Playgroud)

最好检查属性是否是undefined第一个,因为每个点击事件背后都没有数据.


mag*_*rth 6

我无法使用该onclick方法.

但我终于设法使用该click方法运行它:

$("#canvas_id").click(function(e) {
   var activeBars = myBarChart.getBarsAtEvent(e); 
   console.log(activeBars[0]);
});
Run Code Online (Sandbox Code Playgroud)

注意:此示例如果对于条形图 - 其他图表具有稍微不同的方法来检索点(请参阅文档).


小智 6

如果你使用新的ChartJs版本使用这个:

canvas.onclick = function(evt){
   var activePoints = myLineChart.getElementsAtEvent(evt);
};
Run Code Online (Sandbox Code Playgroud)


Rog*_*ill 5

迄今为止提供的答案接近正确的解决方案,但不完整。您需要使用 getElementsAtEvent() 来获取正确的元素,但这会为您提供位于单击的 x-index 处的元素集合。即使您使用多个数据集,这也可能是多个值,每个数据集一个。

要找出要从中提取的正确数据集,请调用 getDatasetAtEvent() 方法。这将返回包含单击的数据集元素的元素列表。从其中任何一个中选择数据集 Id,它们都是相同的 Id。

将两者放在一起,您就可以调用您需要找出被单击元素中包含的数据。在初始化数据集时传入的不仅仅是 x 和 y 值,这将使您可以使用此事件执行各种巧妙的技巧。(例如,触发包含有关事件的更详细信息的弹出窗口)

可能有一种更简洁的方法来获取这些数据,但我没有发现它在图表文档和票证周围乱七八糟。也许他们会在未来的版本中添加它。

// chart_name is whatever your chart object is named. here I am using a
// jquery selector to attach the click event.
$('#' + chart_name).click(function (e)
{
    var activePoints = myChart.getElementsAtEvent(event);
    var activeDataSet = myChart.getDatasetAtEvent(event);

    if (activePoints.length > 0)
    {
         var clickedDatasetIndex = activeDataSet[0]._datasetIndex;
         var clickedElementIndex = activePoints[0]._index;
         var value = myChart.data.datasets[clickedDatasetIndex].data[clickedElementIndex];
    }
    // todo: add code to do something with value.
});
Run Code Online (Sandbox Code Playgroud)