Extend bar chart on Chart JS 2 into a new type of Chart

后端 未结 3 475
你的背包
你的背包 2021-02-06 18:31

I\'m actualy using Chart JS 2.0.1 to draw charts on a page.

My customers asked me to add a line in a bar chart so that they can see the limit they can\'t go over. Like

3条回答
  •  日久生厌
    2021-02-06 19:09

    This is helpful but I found it not that optimized to add new Dataset just for a line that is actually not a data.

    I finally suceeded in creating the new type that extend the bar type and add a line if the value is provided.

    // Store the original Draw function
    var originalLineDraw = Chart.controllers.bar.prototype.draw;
    // extend the new type
    Chart.helpers.extend(Chart.controllers.bar.prototype, {
        draw: function () {
        // use the base draw function
        originalLineDraw.apply(this, arguments);
    
        // get chart and context
        var chart = this.chart;
        var ctx = chart.chart.ctx;
    
        // get lineAtValue value
        var value = chart.config.lineAtValue;
    
        // stop if it doesn't exist
        if (typeof value === "undefined") {
            return;
        }
    
        // draw the line
        var xaxis = chart.scales['x-axis-0'];
        var yaxis = chart.scales['y-axis-0'];
        ctx.save();
        ctx.beginPath();
        ctx.moveTo(xaxis.left, yaxis.getPixelForValue(value));
        ctx.strokeStyle = '#ff0000';
        ctx.lineTo(xaxis.right, yaxis.getPixelForValue(value));
        ctx.stroke();
        ctx.restore();
    
        }
    });
    

    But thank you for your help =)

提交回复
热议问题