0

I'm building a scatter chart using Chart.JS(latest version), one of the behaviours I'm trying to implement is clicking on a single point and highlighting it by changing the background color of the selected point.

I've used the getElementsAtEvent method from the Chart.JS API in order to get the active element and change it's background. For a brief moment I can see it changing the color but it returns to its original color and all the other points now have the color I wanted to apply to the selected one... I tried various approaches to this, using the updated and render methods but with no desired result...

Here's the code inside the function that'll run onClick

function (evt, activeElements, chart) {
  const selectedPoint = chart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true);

  selectedPoint[0].element.options.backgroundColor = '#fa6400';

  chart.update();
}

Here's a fiddle https://jsfiddle.net/dc3x70yg/1/

Thanks in advance

JPRB
  • 5
  • 3

1 Answers1

0

You can define the option pointBackgroundColor on the dataset. When the user clicks on a point, you recreate pointBackgroundColor, but now use an array that contains the desired color for each point.

Please take a look at your amended code below and see how it works.

new Chart('myChart', {
  type: 'scatter',
  data: {
    datasets: [{
      label: '# of Votes',
      data: [{ x: -10, y: 0 }, { x: 0, y: 10 }, { x: 10, y: 5 }, { x: 0.5, y: 5.5 }],
      pointBackgroundColor: '#ddd',
      pointRadius: 5,
    }]
  },
  options: {
    onClick: (event, elements, chart) => {
      const dataset = chart.data.datasets[0];     
      dataset.pointBackgroundColor = dataset.data.map((v, i) => i == elements[0]?.index ? '#fa6400': '#ddd');
      chart.update();
    },
    scales: {
      y: {
        beginAtZero: true
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<canvas id="myChart" width="400" height="200"></canvas>
uminder
  • 23,831
  • 5
  • 37
  • 72