Chart.js 2.0 - vertical lines

前端 未结 3 2208
萌比男神i
萌比男神i 2020-12-14 03:33

Can anyone tell me how to extend Chart.js v2.0. I need vertical lines in a line chart and I want to implement something similar to http://jsfiddle.net/dbyze2ga/.



        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-14 03:40

    UPDATE: See https://stackoverflow.com/a/45092928/360067 for a simpler and more robust solution using the Chart Annotations plugin.

    You can extend the line type to add support for drawing a line


    Preview


    Script

    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();
        }
      }
    });
    

    and then

    var config = {
      type: 'line',
      data: {
        labels: ...
        datasets: [
            ...
        ],
        lineAtIndex: 2
      }
    };
    

    Fiddle - http://jsfiddle.net/mn8x6fso/

提交回复
热议问题