简体   繁体   English

如何获取Chartjs中单击区域的索引?

[英]How to get know index of the area clicked in chartjs?

I have a chart which not necessarily have element at a specified index, but I want to know the index of the area which is clicked. 我有一个图表,它不一定在指定的索引处具有元素,但是我想知道被单击区域的索引。

在此处输入图片说明

If I hover on an area which don't have an element it shows me the tooltip assigned to the area. 如果我将鼠标悬停在没有元素的区域上,则会显示分配给该区域的工具提示。 I just need the same with click and get the index of the area. 我只需要单击并获得该区域的索引即可。

In chart js options you can have onClick event , you can read here ChartJS onClick . 在chart js选项中,您可以拥有onClick事件,您可以在此处阅读ChartJS onClick

Using the onClick you will the get the event and you can check the below code to get the index. 使用onClick您将获取事件,您可以检查以下代码以获取索引。

Addition to it the x and y value are also logged. 除此以外,还将记录x和y值。

i hope the below code will solve your issue. 我希望以下代码能解决您的问题。

 var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["2015-01", "2015-02", "2015-03", "2015-04", "2015-05", "2015-06", "2015-07", "2015-08", "2015-09", "2015-10", "2015-11", "2015-12"], datasets: [{ label: '# of Tomatoes', data: [12, 19, 3, 5, 2, 3, 20, 3, 5, 6, 2, 1], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)', 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { responsive: false, onClick: function(c,i){ e = i[0]; console.log("index",e._index) var x_value = this.data.labels[e._index]; var y_value = this.data.datasets[0].data[e._index]; console.log("x value",x_value); console.log("y value",y_value); }, scales: { xAxes: [{ ticks: { maxRotation: 90, minRotation: 80 } }], yAxes: [{ ticks: { beginAtZero: true } }] } } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script> <canvas id="myChart"></canvas> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM