【问题标题】:Chart.JS Vertical Line with Moment.JS Horizontal AxisChart.JS 垂直线与 Moment.JS 水平轴
【发布时间】:2025-12-31 13:05:07
【问题描述】:

有没有办法使用 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'];

如果我能够解决这个问题,我会在此处发布一个工作小提琴,以供将来处理同一项目的任何用户使用。

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

【问题讨论】:

    标签: chart.js chart.js2


    【解决方案1】:

    我尝试了多个插件,但没有一个可以处理带有 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'],
     }
    

    【讨论】: