1👍
✅
Maybe to simply, you could leverage on onClick
option of chartjs, instead of activate the onclick
on the canvas. The onClick
option can also pass to you the clicked element and you don’t have to invoke the getElementByEvent
.
const xData = ['meta', 'codepen', 'github'];
const yData = [10,18,22];
const ctx = document.getElementById("myChart");
const polarChart = new Chart(ctx, {
type: 'polarArea',
data: {
labels: xData,
datasets: [{
data: yData,
backgroundColor: "rgba(50, 50, 50,0.7)",
}]
},
options: {
onClick(event, elements) {
if (elements.length === 1) {
const selected = xData[elements[0]._index];
// doesn't open the window because not allowed here
window.alert(`https://www.instagram.com/${selected}`);
}
}
}
});
.myChartDiv {
max-width: 600px;
max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
<div class="myChartDiv">
<canvas id="myChart" width="600" height="400"></canvas>
</div>
0👍
I may have figured out a solution, but not sure if it’s the most robust. This is working in a CodePen, but not in the Stack Overflow snippet for me.
var canvasP = document.getElementById("polarChart");
const xData = ['meta', 'codepen', 'github'];
const yData = [10,18,22];
const polarChart = new Chart("polarChart", {
type: 'polarArea',
data: {
labels: xData,
datasets: [{
data: yData,
backgroundColor: "rgba(50, 50, 50,0.7)",
}]
}
});
canvasP.onclick = function(e) {
var slice = polarChart.getElementAtEvent(e);
if (!slice.length) return; // return if not clicked on slice
var label = slice[0]._model.label;
for(let i=0; i<xData.length; i++) {
let currUser = xData[i];
switch (label) {
case xData[i]:
window.open(`https://www.instagram.com/${currUser}`);
break;
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<canvas id="polarChart"></canvas>
Source:stackexchange.com