Home > Net >  How can I change the cursor on pie chart segment hover in ChartJS 3?
How can I change the cursor on pie chart segment hover in ChartJS 3?

Time:12-02

In a situation similar to enter image description here

How can I access the segment element to apply styling?

CodePudding user response:

You can get the chart instance from the event which has the canvas on which you can target the mouse like so:

const options = {
  type: 'pie',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    }]
  },
  options: {
    onHover: (evt, activeEls) => {
      activeEls.length > 0 ? evt.chart.canvas.style.cursor = 'pointer' : evt.chart.canvas.style.cursor = 'default';
    }
  }
}

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.1/chart.js"></script>
</body>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related