I'm not sure this is possible without doing something along the line of: Create links in HTML canvas but let's make sure.
Is there a way to (relatively) simply turn Chart.js labels into links? The chart in question is the radar chart: http://www.chartjs.org/docs/#radar-chart (So far I've been using the legend for that, works fine with a little library modification, but now I should use the labels themselves.)
You can listen to the click event and then loop through all the pointLabels check if the click is in that box. If this is the case you get the corresponding label from the array containing all the labels.
Then you can open use window.location = link
or window.open(link)
to go to your link.
Example that searches the color on google on click:
const options = {
type: 'radar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'orange'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'pink'
}
]
},
options: {
onClick: (evt, activeEls, chart) => {
const {
x,
y
} = evt;
let index = -1;
for (let i = 0; i < chart.scales.r._pointLabelItems.length; i++) {
const {
bottom,
top,
left,
right
} = chart.scales.r._pointLabelItems[i];
if (x >= left && x <= right && y >= top && y <= bottom) {
index = i;
break;
}
}
if (index === -1) {
return;
}
const clickedLabel = chart.scales.r._pointLabels[index];
window.open(`https://www.google.com/search?q=color%20${clickedLabel}`); // Blocked in stack snipet. See fiddle
console.log(clickedLabel)
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>
Fiddle: https://jsfiddle.net/Leelenaleee/fnqr4c7j/22/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With