如何在图表js中添加多X轴自定义行

时间:2017-12-30 11:58:04

标签: javascript chart.js

我需要在图表js中绘制多个X轴垂直自定义行,如果可以根据X轴值绘制多行,我从jsfiddle链接http://jsfiddle.net/mn8x6fso/得到了一个示例用这个例子。或者如果可能的话在javascript中?。

1 个答案:

答案 0 :(得分:0)

这是一个解决方法:

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'];

      var aaxis = chart.scales['x-axis-0'];
      var yyaxis = 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.moveTo(aaxis.getPixelForValue(undefined, index + 1), yyaxis.top);
      ctx.strokeStyle = '#cc0000';
      ctx.lineTo(aaxis.getPixelForValue(undefined, index + 1), yyaxis.bottom);

      ctx.stroke();
      ctx.restore();
    }
  }
});

var config = {
  type: 'line',
  data: {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
      label: "My First dataset",
      data: [65, 0, 80, 81, 56, 85, 40],
      fill: false
    }],
    lineAtIndex: 2
  }
};

var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);