Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

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

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. The second monday to friday a gray background. The thirth a white bg again. And the fourth weeks with monday to friday to have a gray background color. What Im talking about is the background of the graph. Is there a way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Chart.js clears the canvas before drawing (or redrawing) a chart.

We can jump in on this and draw our background once the chart is cleared. Just extend the Line chart and override the clear function in the initialize override.


Preview

enter image description here


Script

Chart.types.Line.extend({
    name: "LineAlt",
    initialize: function(data){
        Chart.types.Line.prototype.initialize.apply(this, arguments);

        // keep a reference to the original clear
        this.originalClear = this.clear;
        this.clear = function () {

            this.originalClear();

            // 1 x scale unit
            var unitX = this.datasets[0].points[1].x - this.datasets[0].points[0].x;

            var yTop = this.scale.startPoint;
            var yHeight = this.scale.endPoint - this.scale.startPoint;

            // change your color here
            this.chart.ctx.fillStyle = 'rgba(100,100,100,0.8)';

            // we shift it by half a x scale unit to the left because the space between gridline is actually a shared space
            this.chart.ctx.fillRect(this.datasets[0].points[5].x - 0.5 * unitX, yTop, unitX * 5, yHeight);
            this.chart.ctx.fillRect(this.datasets[0].points[15].x - 0.5 * unitX, yTop, unitX * 5, yHeight);
        }
    }
});

Then just use LineAlt instead of Line

var myNewChart = new Chart(ctx).LineAlt(data);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...