How to change chart's backgroundColor for specific dataset with onclick event using ChartJS

Viewed 60

// Set Chart Global Variables
let x_values = [0];
let y_values = [0];
let new_number = 0;
let index = 0;

// Intialize The Chart Canvas
let ctx = document.getElementById('chart_canvas').getContext('2d');

// Create New Line Chart
my_chart = new Chart(ctx, {
  type: "line",
  data: {
    labels: [x_values[0]],
    datasets: [{
      backgroundColor: [],
      fill: true,
      pointStyle: "circle",
      label: "Values",
      data: [y_values[0]]
    }]
  }
});

// ------ Local Functions ------

function add() {
  index = x_values.length;
  new_number += 10;

  my_chart.data.labels.push(index);
  x_values.push(index);

  my_chart.data.datasets.forEach((dataset) => {
    dataset.data.push(new_number);

    //The line below might be wrong since it is not changing the background color.
    dataset.backgroundColor.push("#88c0d080");
  });

  my_chart.update();
}

function subtract() {
  index = x_values.length;
  new_number -= 10;

  my_chart.data.labels.push(index);
  x_values.push(index);

  my_chart.data.datasets.forEach((dataset) => {
    dataset.data.push(new_number);

    //This line below might be wrong since it is not changing the background color.
    dataset.backgroundColor.push("#bf616a80");
  });

  my_chart.update();
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Testing Chart.js Line Chart</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js" integrity="sha512-sW/w8s4RWTdFFSduOTGtk4isV1+190E/GghVffMA9XczdJ2MDzSzLEubKAs5h0wzgSJOQTRYyaz73L3d6RtJSg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>

<body>
  <button type="button" onclick="add()" id="btnAdd">Add 10</button>
  <button type="button" onclick="subtract()" id="btnSubtract">Subtract 10</button>
  <canvas id="chart_canvas">Your browser does not support the HTML5 canvas tag.</canvas>
</body>

</html>

Expected Behavior:

  • When the "Add 10" button is clicked, a new point entry needs to be added with a backgroundColor fill color of teal (#88c0d080).

  • When the "subtract 10" button is clicked, a new point entry needs to be added with a backgroundColor fill color of red (#bf616a80).

Current Behavior:

  • Only the point background color is being changed rather than the backgroundColor fill color.

Your help will be much appreciated.

1 Answers

You can use segment styling that update dynamicly when you add new data:

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderColor: 'orange',
      fill: true,
      segment: {
        backgroundColor: (ctx) => (ctx.p0.parsed.y > ctx.p1.parsed.y ? 'red' : 'teal')
      }
    }]
  },
  options: {}
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
const c = new Chart(ctx, options);

document.getElementById('add').addEventListener('click', () => {
  c.data.labels.push(c.data.labels.length);
  c.data.datasets[0].data.push(c.data.datasets[0].data[c.data.datasets[0].data.length - 1] + 10)
  c.update()
});

document.getElementById('subb').addEventListener('click', () => {
  c.data.labels.push(c.data.labels.length);
  c.data.datasets[0].data.push(c.data.datasets[0].data[c.data.datasets[0].data.length - 1] - 10)
  c.update()
});
<body>
  <button id="add">
    Add 10
    </button>
  <button id="subb">
    Subtract 10
    </button>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
</body>

Related