Chart.js - draw horizontal line

后端 未结 4 936
渐次进展
渐次进展 2020-11-27 19:05

I would like to draw a horizontal line in a chart using Chart.js. But I\'m not able to do it.

I\'ve read this question - Chart.js — drawing an arbitrary vertical lin

4条回答
  •  醉梦人生
    2020-11-27 19:47

    If you need many lines with certain Y value, try this code

    var data = {
        labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
        datasets: [{
            data: [12, 3, 2, 1, 8, 8, 2, 2, 3, 5, 7, 1]
        }]
    };
    
    var ctx = document.getElementById("LineWithLine").getContext("2d");
    
    Chart.types.Line.extend({
        name: "LineWithLine",
        draw: function () {
            Chart.types.Line.prototype.draw.apply(this, arguments);
    
            var lines = this.options.limitLines;
    
            for (var i = lines.length; --i >= 0;) {
    
                var xStart = Math.round(this.scale.xScalePaddingLeft);
                var linePositionY = this.scale.calculateY(lines[i].value);
    
                this.chart.ctx.fillStyle = lines[i].color ? lines[i].color : this.scale.textColor;
                this.chart.ctx.font = this.scale.font;
                this.chart.ctx.textAlign = "left";
                this.chart.ctx.textBaseline = "top";
    
                if (this.scale.showLabels && lines[i].label) {
                    this.chart.ctx.fillText(lines[i].label, xStart + 5, linePositionY);
                }
    
                this.chart.ctx.lineWidth = this.scale.gridLineWidth;
                this.chart.ctx.strokeStyle = lines[i].color ? lines[i].color : this.scale.gridLineColor;
    
                if (this.scale.showHorizontalLines) {
                    this.chart.ctx.beginPath();
                    this.chart.ctx.moveTo(xStart, linePositionY);
                    this.chart.ctx.lineTo(this.scale.width, linePositionY);
                    this.chart.ctx.stroke();
                    this.chart.ctx.closePath();
                }
    
                this.chart.ctx.lineWidth = this.lineWidth;
                this.chart.ctx.strokeStyle = this.lineColor;
                this.chart.ctx.beginPath();
                this.chart.ctx.moveTo(xStart - 5, linePositionY);
                this.chart.ctx.lineTo(xStart, linePositionY);
                this.chart.ctx.stroke();
                this.chart.ctx.closePath();
            }
        }
    });
    
    new Chart(ctx).LineWithLine(data, {
        datasetFill : false,
        limitLines: [
            {
                label: 'max',
                value: 17,
                color: 'rgba(255, 0, 0, .8)'
            },
            {
                label: 'min',
                value: 1
            },
            {
                value: 7,
                color: 'rgba(0, 255, 255, .8)'
            }
        ],
    });
    

    http://jsfiddle.net/vsh6tcfd/3/

提交回复
热议问题