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

时间:2016-11-27 07:32:19

标签: chart.js chart.js2

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

我已经在网上看到了一些例子(see this related question),但是,当使用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();
    }
  }
});

这是一个表明问题的小提琴: https://jsfiddle.net/harblz/0am8vehg/

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

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

如果我能够弄清楚这一点,我会在这里发布一个工作小提琴,以便将来用户处理同一个项目。

感谢您抽出时间阅读本文:)

1 个答案:

答案 0 :(得分:1)

我尝试了多个插件,但是没有一个插件可以处理时间类型为 的笛卡尔坐标轴的图表。我的简单解决方案:

首先在全局范围内注册图表插件

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'],
 }