Chartjs-Resizable/Expendable box annotation in ChartJs

1👍

Yes, you can dive into the options part of your chart object, adjust the config for your annotation and then call chart.update() this will update the annotation.

Example:

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderWidth: 1
    }]
  },
  options: {
    plugins: {
      annotation: {
        annotations: {
          box1: {
            type: "box",
            xMin: 1,
            xMax: 2,
            yMin: 5,
            yMax: 10,
            backgroundColor: "rgba(255, 99, 132, 0.25)"
          }
        }
      }
    }
  }
}

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

document.getElementById("tt").addEventListener("click", () => {
  chart.options.plugins.annotation.annotations.box1.yMax = 16;
  chart.update();
});

document.getElementById("rr").addEventListener("click", () => {
  chart.options.plugins.annotation.annotations.box1.yMax = 8;
  chart.update();
});
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <button id="tt">Update annotation to 16</button>
  <button id="rr">Update annotation to 8</button>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.0/chart.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/1.0.2/chartjs-plugin-annotation.js"></script>
</body>

Leave a comment