I'm using chart.js to make a radar chart that the user should be able to interact on their own. The idea is that if the user clicks on the red spot, the app should know whether the green spot is the closest intersection of ticks and angle lines, so that it can change the dataset value at index 1 (corresponding to B) from 2 (corresponding to mid-low) to 4 (mid-high).
And it's set up like this:
const chartData = {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
fill: true,
backgroundColor: 'rgba(6,211,248,0.5)',
borderColor: 'rgb(6,211,248)',
data: mockData.presetValues.a,
}]
};
const chartConfig = {
type: 'radar',
data: chartData,
options: {
elements: {
line: {
borderWidth: 3
},
},
scales: {
r: {
min: 0,
max: 5,
ticks: {
stepSize: 1,
callback: function (value) {
return ['none', 'low', 'mid-low', 'mid', 'mid-high', 'high'][value]
}
},
grid: {
circular: true,
lineWidth: 5
},
angleLines: {
color: 'black',
}
}
},
plugins: {
legend: {
display: false
}
},
events: ['click']
}
};
const actionChart = new Chart(
canvas,
chartConfig
);
Then I have a listener set up for it like so:
canvas.addEventListener('click', handleChartClick)
And finally I have a handler like this, which is where my problem is:
function handleChartClick(ev) {
let clickPosition = Chart.helpers.getRelativePosition(ev, actionChart);
console.log(clickPosition);
//Find closest tick to click and change values in dataset before refresh
}
After hours of scouring the documentation and this site, I can not find a way of correlating the position of the click that I receive from the getRelativePosition method with the position of the intersections between the angle lines and the ticks. Once I have those two pieces of information I can modify the dataset and refresh, but I'd greatly appreciate if anyone could help me figure out how to get the closest intersection to the click.
You could use onClick option of chart in order to catch click event (instead of adding a listener to the canvas). In this way the passed event is already normalized.
The callback could be something like that, in order to have the closest tick:
options: {
...
onClick(event, elements, chart) {
const scale = chart.scales.r;
const posY = Math.abs(scale.getDecimalForPixel(event.y) - 0.5);
const posX = Math.abs(scale.getDecimalForPixel(event.x) - 0.5);
const scalePosition = Math.max(posY, posX);
const value = Math.round(scalePosition * 10);
console.log(['none', 'low', 'mid-low', 'mid', 'mid-high', 'high'][value]); // shows value
},
...