Chart.JS - 多个 - 框 - 注释 - 只显示最后一个框

问题描述

Chart.JS - 多个 - 框 - 注释 - 只显示最后一个

解决方法

两件事。首先,您尝试以 v2 方式定义 scales 配置,这不再起作用。您不应该将比例定义为时间,因为您不使用时间对象,要使用 timeScale,您需要提供 moment/luxon 或任何其他日期库对象和相应的日期适配器,以便 chart.js 可以自动为比例打勾。>

同样如chart.js 注释文档(https://www.chartjs.org/chartjs-plugin-annotation/guide/types/box.html#configuration) 中所定义,您需要为xMinxMax 道具提供一个数字,以便您可以为其提供标签,您提供它是需要绘制它的位置的索引。

现场示例:

var timeFormat = {
  'millisecond': 'HH:mm','second': 'HH:mm','minute': 'HH:mm','hour': 'HH:mm','day': 'HH:mm','week': 'HH:mm','month': 'HH:mm','quarter': 'HH:mm','year': 'HH:mm',};


const options = {
  type: 'line',data: {
    labels: ['6:38','6:38','6:39','6:40','6:41','6:42','6:43','6:44','6:45','6:46','6:47','6:48','6:49','6:50','6:51','6:52','6:53','6:54','10:54'],datasets: [{
      label: '# of Votes',data: [12,19,3,5,2,12,3],borderWidth: 1
    }]
  },options: {
    scales: {
      // New way of defining scales
      x: {
        grid: {
          color: 'red'
        }
      },y: {}
    },plugins: {
      annotation: {
        annotations: {
          box1: {
            type: "box",drawTime: "beforeDatasetsDraw",xMin: '6:39',// doesnt work,needs point index
            xMax: '7:00',needs point index
            yMin: 2,yMax: 10,backgroundColor: "red",},box2: {
            type: "box",xMin: 7,xMax: 10.14,yMin: 2,backgroundColor: "blue",}
        }
      }
    }
  }
}

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>

带有矩的 time 比例实现示例的基本小提琴:https://jsfiddle.net/Leelenaleee/bza0v3rc/11/