如何使用 ChartJS V > 2.0 中的 onClick 事件获取 X、Y 坐标相对于图表?
取this JSFiddle举个例子。在 #canvas
中创建散点图。单击图表中心时,我应该得到 0、0 即使那里没有数据点。
最佳答案
对于 future 的读者,一个可行的解决方案:
chartClicked(event){
var yTop = this.chart.chartArea.top;
var yBottom = this.chart.chartArea.bottom;
var yMin = this.chart.scales['y-axis-0'].min;
var yMax = this.chart.scales['y-axis-0'].max;
var newY = 0;
if (event.offsetY <= yBottom && event.offsetY >= yTop) {
newY = Math.abs((event.offsetY - yTop) / (yBottom - yTop));
newY = (newY - 1) * -1;
newY = newY * (Math.abs(yMax - yMin)) + yMin;
};
var xTop = this.chart.chartArea.left;
var xBottom = this.chart.chartArea.right;
var xMin = this.chart.scales['x-axis-0'].min;
var xMax = this.chart.scales['x-axis-0'].max;
var newX = 0;
if (event.offsetX <= xBottom && event.offsetX >= xTop) {
newX = Math.abs((event.offsetX - xTop) / (xBottom - xTop));
newX = newX * (Math.abs(xMax - xMin)) + xMin;
};
console.log(newX, newY);
};
关于javascript - 在 ChartJS 中获取 X、Y onClick 图表坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46107009/