当用户点击图表时,我想从ChartJS的折线图中接收x,y值。 与通常讨论技术相比,模具难度是,我需要从图表中的任何位置接收x,y值,而不是在我点击数据集中的某些样本时。
所以当我点击一些空位时,我需要知道它的x和y轴值。
在其中有一个评论的例子,我在哪里sutck:
var randomInt = function() {
return (Math.random() * 100) - 50;
};
//needs it for the test
var labels = ["Management", "Finance", "Human Resources", "Business Development and Marketing", "Information Technology", "Professional Development and Training", "Knowledge Management", "Logistics", "Support", "Business Services", "Other"];
var datas = [{
x: randomInt(),
y: randomInt(),
}, {
x: randomInt(),
y: randomInt(),
}, {
x: randomInt(),
y: randomInt(),
}, {
x: randomInt(),
y: randomInt(),
}, {
x: randomInt(),
y: randomInt(),
}, {
x: randomInt(),
y: randomInt(),
}, {
x: randomInt(),
y: randomInt(),
}];
var scatterChartData = {
labels: labels,
datasets: [{
label: "My First dataset",
data: datas
}]
};
var ctx = document.getElementById("canvas").getContext("2d");
var myScatter = new Chart.Scatter(ctx, {
data: scatterChartData,
options: {
title: {
display: true,
text: 'Chart.js Scatter Chart'
},
scales: {
xAxes: [{
position: 'bottom',
gridLines: {
zeroLineColor: "rgba(0,255,0,1)"
},
scaleLabel: {
display: true,
labelString: 'x axis'
}
}],
yAxes: [{
position: 'right',
gridLines: {
zeroLineColor: "rgba(0,255,0,1)"
},
scaleLabel: {
display: true,
labelString: 'y axis'
}
}]
}
}
});
//
canvas.onclick = function(evt){
//HERE I have the x,y pixel coordinates inside the evt object.
//How to get the x,y values from the x and y axis??
//this works only if I click on one of the samples...
var activePoints = myScatter.getElementsAtEvent(evt);
var firstPoint = activePoints[0];
if(firstPoint !== undefined){
var label = myScatter.data.labels[firstPoint._index];
var value = myScatter.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
alert(label + ": " + value.x);
alert(label + ": " + value.y);
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.0-beta2/Chart.min.js"></script>
<div>
<div>
<canvas id="canvas"></canvas>
</div>
</div>
答案 0 :(得分:0)
我发现至少有一种提取y轴值的方法。 x轴值的计算应该类似:
//inside the click callback...
var scaler=that.chart.scales['y-axis-0'];
var chart_height_px=scaler.bottom+scaler.top;
var y=evt.clientY-that.canvas[0].getBoundingClientRect().top-scaler.top;
var yval=scaler.max-y/scaler.height*(scaler.max-scaler.min);
console.log("value clicked: %o, ypx: %o", yval, y);
that.trigger("onTickerYClick", yval);