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

时间:2014-08-26 20:42:33

标签: javascript charts onclick linechart chart.js

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

研究:

我浏览了documentation of 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. };

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

我的代码:(在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?");
};

对于那些很难看到图表的人来说,你去了:

enter image description here

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

4 个答案:

答案 0 :(得分:7)

更改此行

document.getElementById('roomForChart').innerHTML += htmlForGraph;

到这个

holder = document.getElementById('roomForChart');
holder.innerHTML += htmlForGraph;

进一步你会得到你的片段,修改一下

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?");
};

在onclick处理程序中添加console.log(activePoints);以查看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

可以按以下方式访问它们

activePoints[0].label
activePoints[0].x
activePoints[0].y
activePoints[0].value

最好先检查属性是否为undefined,因为每次点击事件都没有数据。

答案 1 :(得分:6)

我无法使用onclick方法。

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

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

注意:此示例如果是条形图 - 其他图表的方法略有不同以检索点(请参阅文档)。

答案 2 :(得分:5)

如果你使用新的ChartJs版本,请使用:

var url = //Your URL;

  var config = {
    async:true
  };

  var promise= $http.get(url, config);
     promise.then(
     function (result) 
     {
       return result.data;
     },
     function (error) 
     {
       return error;
     }
    );

答案 3 :(得分:2)

迄今为止提供的答案接近正确的解决方案,但不完整。您需要使用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.
});