Chartjs-Change color of a single point by clicking on it โ€“ Chart.JS

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>

Leave a comment