0

I have a doughnut chart with HTML elements inside.

I would like to call a function when an element is clicked inside the chart.

Check out the screenshot below. I highlighted the element in red color.

enter image description here

I am aware that we can set the onClick event in chartJS options object like

options: { onClick: click_chart_function }

And I can get the chart onclick event just fine. But it is related to chart canvas click but not the element itself.

Any help is greatly appreciated.


Some debug code below:

function click_chart_function(event, array){

    let click_elm = CHART.getElementAtEvent(event)  

     console.log(event, array, click_elm)
...
<canvas id="chart" width="250" height="250"></canvas>


<div id="chart-text-container">
   <div style="z-index: 1000 !important;" onclick="console.log('hello world - container');">
      <i style="z-index: 1000 !important;" class="icon" onclick="console.log('hello world - inner');"></i>
   </div>

   <div id="chart-text-size"></div>
   <div id="chart-text-label"></div>
</div>
#chart-text-container {
    margin-top: -165px; 
    margin-bottom: 120px; /* compensate -100px for below elements */
    display: none;
    text-align: center;
    z-index: 1000 !important;
}
Systems Rebooter
  • 1,281
  • 2
  • 14
  • 30

1 Answers1

0

It turned to be not a Chart.js issue, but a <canvas> element nature that prevents events.

One possible solution would be to get x,y coordinates offset from the chart.js click event and do some math to represent the element inside the chart canvas.

For example:

var x = e.offsetX 
var y = e.offsetY

if (x > 120 && x < 130 && y > 85 && y < 100)
   element_clicked()

Good reads:

Hit Region Detection For HTML5 Canvas And How To Listen To Click Events On Canvas Shapes

StackOverflow: How do I add a simple onClick event handler to a canvas element?

Systems Rebooter
  • 1,281
  • 2
  • 14
  • 30