Chart.JS 垂直线 Moment.JS 水平轴

Chart.JS Vertical Line with Moment.JS Horizontal Axis

有没有办法使用 Chart.JS 2.0 创建垂直线(事件线、相位变化)?

我在网上看过一些例子 (),但是,当使用 Moment.js 创建水平轴时,不可能给 LineAtIndex 一个 moment.js 日期在那个日期创建一行。

    var originalLineDraw = Chart.controllers.line.prototype.draw;
Chart.helpers.extend(Chart.controllers.line.prototype, {
  draw: function() {
    originalLineDraw.apply(this, arguments);

    var chart = this.chart;
    var ctx = chart.chart.ctx;

    var index = chart.config.data.lineAtIndex;
    if (index) {
      var xaxis = chart.scales['x-axis-0'];
      var yaxis = chart.scales['y-axis-0'];

      ctx.save();
      ctx.beginPath();
      ctx.moveTo(xaxis.getPixelForValue(undefined, index), yaxis.top);
      ctx.strokeStyle = '#ff0000';
      ctx.lineTo(xaxis.getPixelForValue(undefined, index), yaxis.bottom);
      ctx.stroke();
      ctx.restore();
    }
  }
});

这里有一个 fiddle 演示问题: https://jsfiddle.net/harblz/0am8vehg/

我认为我的问题是我没有正确理解这段代码:

var xaxis = chart.scales['x-axis-0'];
var yaxis = chart.scales['y-axis-0'];

如果我能解决这个问题,我会 post 在这里工作 fiddle 供将来处理同一项目的用户使用。

感谢您花时间阅读本文:)

我尝试了多个插件,但 none 可以处理具有 time 类型笛卡尔轴的图表。我相当简单的解决方案:

首先全局注册图表插件

Chart.plugins.register({
  drawLine: function (chart, xValue, color = 'rgba(87,86,86,0.2)') {
    const canvas = chart.chart
    const context = canvas.ctx

    context.beginPath()
    context.moveTo(xValue, 6) // top
    context.lineTo(xValue, canvas.height - 73) // bottom
    context.strokeStyle = color
    context.stroke()
  },

  afterDraw: function (chart) {
    const xScale = chart.scales['x-axis-0']

    if (chart.options.verticalLine) {
      chart.options.verticalLine.forEach((line) => {
        const xValue = xScale.getPixelForValue(line)

        if (xValue) {
          this.drawLine(chart, xValue)
        }
      })
    }
  }
})

然后将 verticalLine 数组添加到您的图表定义中:

options: {
   scales: { xAxes: [{ type: 'time' }] },
   verticalLine: ['2019-04-1', '2019-07-01', '2019-10-01'],
 }