如何获取折线图的日期标签?



我在应用程序中使用图表线.js(版本:2.7.2(,单击某些元素时打开对话框,并且 我需要获取当前元素的标签(xAxes上的日期(。谷歌搜索我找到了示例并尝试制作如下:

var lineCanvas = document.getElementById("canvasVotesByDays");
var ctx = lineCanvas.getContext('2d');
var lineChart = new Chart(ctx, {
type: 'line',
data: {
labels: monthsXCoordItems,
datasets: [
{
label: 'Correct Votes',
...
lineCanvas.onclick = function (e) {
console.log("INSIDE lineChart::")
console.log(lineChart)
var slice = lineChart.getPointsAtEvent(e);
...

但是在最后一行我得到错误:

Uncaught TypeError: lineChart.getPointsAtEvent is not a function
at HTMLCanvasElement.lineCanvas.onclick 

在控制台中,我看到了 lineChart 对象的优先级: https://i.stack.imgur.com/q8zuJ.jpg

为什么出错以及如何获取标签属性?

谢谢!

伊万 我用过你的jsfidlle:jsfiddle.net/e8n4xd4z/19925 你已经完成了控制台.log 对于所有变量,
所以我看到你正在使用数组作为对象,看这里

var firstPoint = lineChart.getElementAtEvent(e)

折线图返回索引为 0 的数组,但您直接访问该属性, 您正在使用firstPoint._index,但实际上该属性存在于更深的层次上,这意味着它处于firstPoint[0]._index

我也分叉了你的 JSFIDDLE,这是我的 JSFIDDLE,或者我也在内置的 StackOverflow 片段中实现了你的示例,请参见下面的工作示例:

var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
	    {
	      label: '# of Votes',
	      data: [12, 19, 3, 5, 2, 3],
	      borderWidth: 1
	    },	
	    {
label: '# of Points',
	      data: [7, 11, 5, 8, 3, 7],
	      borderWidth: 1
	    }
	  ]
},
options: {
	scales: {
	yAxes: [{
ticks: { 
reverse: false
}
}]
}
} 
};
var lineCanvas = document.getElementById("chartJSContainer");

var ctx = lineCanvas.getContext('2d');
var lineChart = new Chart(ctx, options);
lineCanvas.onclick = function (e) {
var firstPoint  = lineChart.getElementAtEvent(e)[0];
if (firstPoint) {
var first_point_index= firstPoint._index
console.log("+1 first_point_index::")
console.log( first_point_index )
var firstPoint_dataset_index= firstPoint._datasetIndex
console.log("+2 first_point_index::")
console.log( first_point_index )

var label = lineChart.data.labels[firstPoint._index];
console.log("+3 label::")
console.log( label )

var value = lineChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
alert( "label::"+(label) + "  value::"+(value) )
}
}
canvas { 
background-color : #eee;
}
<html>
<head>   
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
</head>
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>
</html>

根据文档,正确的方法似乎是getElementAtEvent或getElementsAtEvent

function clickHandler(evt) {
var firstPoint = myChart.getElementAtEvent(evt)[0];
if (firstPoint) {
var label = myChart.data.labels[firstPoint._index];
var value = myChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
}
}

最新更新