[Chartjs]-ChartJS โ€“ Moving vertical line is display on top of tooltip

5๐Ÿ‘

โœ…

You can use a custom plugin that draws after all the datasets have drawn but before the tooltip is drawn:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        stacked: true
      }]
    },
    plugins: {
      customLine: {
        width: 5,
        color: 'pink'
      }
    }
  },
  plugins: [{
    id: 'customLine',
    afterDatasetsDraw: (chart, x, opts) => {
      const width = opts.width || 1;
      const color = opts.color || 'black'

      if (!chart.active || chart.active.length === 0) {
        return;
      }

      const {
        chartArea: {
          top,
          bottom
        }
      } = chart;
      const xValue = chart.active[0]._model.x

      ctx.lineWidth = width;
      ctx.strokeStyle = color;

      ctx.beginPath();
      ctx.moveTo(xValue, top);
      ctx.lineTo(xValue, bottom);
      ctx.stroke();
    }
  }]
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>

Leave a comment