Chartjs-How can i change a specific bar color in chart.js color chartjs

0πŸ‘

βœ…

I have prepared a sample. Clicking on the bar element, the color picker is visible and when you choose the color, the chart will be updated with new color.

I think it’s better to use onClick option provided by CHART.JS instead of add event listener to the canvas because CHART.JS option is providing the elements affected by the click event.

To simplify the sample, be aware that the backgroundColor must be set as an array with the original colors for each bar (but you can add additional logic to manage it).

let selected = undefined;
const chartData = {
  labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
  datasets: [{
    fill: true,
    backgroundColor:  ['cyan','cyan','cyan','cyan','cyan','cyan','cyan'],
    data: [40, 39, 10, 40, 39, 80, 40],
  }]
};
const ctx = document.getElementById('myChart');
const myChart = new Chart(ctx, {
  type: 'bar',
  data: chartData,
  options: {
    onClick(evt, elements, chart) {
      if (elements.length) {
        selected = elements;
        const colorPicker = document.getElementById("colorPicker");
        colorPicker.click();
      }
    }
  }
});
document.getElementById("colorPicker").addEventListener("change", setColor);
function setColor() {
  if (selected && selected.length) {
    const colorPicker = document.getElementById("colorPicker");
    for (const el of selected) {
      const {datasetIndex, index} = el;
      const dataset = myChart.data.datasets[datasetIndex];
      dataset.backgroundColor.splice(index, 1, colorPicker.value);
    }
    myChart.update();
  }
}
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<html>
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600" height="400"/>
    </div>
    <input id="colorPicker" type="color" style="visibility: hidden;"/>
  </body>
</html>

Leave a comment