首页 文章

在Chart.js 2.0中绘制水平线

提问于
浏览
10

你能帮我看看如何扩展Chart.js v2.0吗?我需要在图表中绘制一些水平线,类似于:http://jsfiddle.net/vsh6tcfd/3/

var originalLineDraw = Chart.controllers.bar.prototype.draw;

Chart.helpers.extend(Chart.controllers.bar.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.left);
      ctx.strokeStyle = '#ff0000';
      ctx.lineTo(xaxis.getPixelForValue(undefined, index), yaxis.right);
      ctx.stroke();
      ctx.restore();
    }
  }
});

var config = {
    type: type,
    data:  jQuery.extend(true, {}, data),
    options: this.chartdata.options,
    lineAtIndex: 2
};

new Chart(ctx, config);

1 回答

  • 18

    选项

    使用chart.js,您有2个选项 .

    • 您可以创建混合图表类型(Example Here) . 这将允许您添加折线图以创建线条 .

    • 您可以创建一个插件(参见下面的示例) .

    选项2将是我推荐的选项,因为它允许您更多地控制线条的外观 .

    修复

    demo of the plugin

    Chart.js现在supports plugins . 这允许您将所需的任何功能添加到图表中!

    要创建插件,您需要在事件发生后运行代码,并根据需要修改图表/画布 . 以下代码应该为您提供一个很好的起点:

    var horizonalLinePlugin = {
      afterDraw: function(chartInstance) {
        var yValue;
        var yScale = chartInstance.scales["y-axis-0"];
        var canvas = chartInstance.chart;
        var ctx = canvas.ctx;
        var index;
        var line;
        var style;
    
        if (chartInstance.options.horizontalLine) {
          for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
            line = chartInstance.options.horizontalLine[index];
    
            if (!line.style) {
              style = "rgba(169,169,169, .6)";
            } else {
              style = line.style;
            }
    
            if (line.y) {
              yValue = yScale.getPixelForValue(line.y);
            } else {
              yValue = 0;
            }
    
            ctx.lineWidth = 3;
    
            if (yValue) {
              ctx.beginPath();
              ctx.moveTo(0, yValue);
              ctx.lineTo(canvas.width, yValue);
              ctx.strokeStyle = style;
              ctx.stroke();
            }
    
            if (line.text) {
              ctx.fillStyle = style;
              ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
            }
          }
          return;
        }
      }
    };
    Chart.pluginService.register(horizonalLinePlugin);
    

相关问题