0

I am using chartjs-plugin-annotation in chartJs with ReactJs. But in box annotation is there a way how can I resize the box so I can expend the min, max value of the annotation.

My option code: `

 options: {
        scales: {
          y: {
            beginAtZero: true
          }
        },
        plugins: {
          autocolors: false,
          annotation: {
            annotations: {
              box1: {
                type: "box",
                xMin: 1,
                xMax: 2,
                yMin: 5,
                yMax: 10,
                backgroundColor: "rgba(255, 99, 132, 0.25)"
              }
            }
          }
        }
      }

`

Here is my code sandbox ReactJs-ChartJs

enter image description here

ppegu
  • 362
  • 2
  • 9
  • 22

1 Answers1

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>
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69
  • yeah, this is fine but is there any way instead of clicking the buttons I can resize the annotation box itself? by mouse - like you crop an image in an image editor? – ppegu Jul 11 '21 at 06:36
  • You can use the `onHover` and `onClick` callbacks chart.js provides but it will be a lot more work to get it nice – LeeLenalee Jul 11 '21 at 08:20