chart.js Line chart with different background colors for each section

后端 未结 4 1007
天涯浪人
天涯浪人 2020-12-09 22:41

Lets say I have a Line chart with mon-fri for 4 weeks. I want that these 4 weeks are diveded in sections. I want the first monday to friday have a white background color. Th

4条回答
  •  失恋的感觉
    2020-12-09 23:46

    I combined @potatopeelings's and @v25's solutions for a chart.js v2 solution. It utilizes the format of @potatopeelings's solution, allowing to use an alternate chart type (LineAlt), and the updated implementation from @v25's solution.

    Chart.controllers.LineAlt = Chart.controllers.line.extend({
        draw: function (ease) {
            if (this.chart.config.options.chartArea && this.chart.config.options.chartArea.backgroundColor) {
                var ctx = this.chart.chart.ctx;
                var chartArea = this.chart.chartArea;
    
                var meta = this.chart.getDatasetMeta(0);
    
                var start = meta.data[1]._model.x;
                var stop  = meta.data[2]._model.x;
    
                ctx.save();
                ctx.fillStyle = this.chart.config.options.chartArea.backgroundColor;
                ctx.fillRect(start, chartArea.top, stop - start, chartArea.bottom - chartArea.top);
                ctx.restore();
            }
    
            // Perform regular chart draw
            Chart.controllers.line.prototype.draw.call(this, ease);
        }
    });
    

    Then you can use the custom chart type just as in @potatopeelings's solution:

    var myNewChart = new Chart(ctx, {type: 'LineAlt', data: data});
    

提交回复
热议问题