flowstacker
flowstacker

Reputation: 115

Background color hides Y labels

Graph

I am changing background of my chart, but when I zoom and drag, the background covers the Y labels. How to solve this?

plugins: [{
                        id:'2',
                        beforeDatasetsDraw: function (chart:any, easing:any) {
                            if (chart.chartArea) {
                            var ctx = chart.ctx;
                            var chartArea = chart.chartArea;
                            let d = data.chart.relay;
                            let e = chart.getDatasetMeta(0)
                            ctx.fillStyle = '#b3ff99';

                            var start!:number;
                            var stop!:number;
                            for(let i = 0; i<d.length; i++) {
                                start=e.data[i].x
                                if (d[i] && d[i+1] === true) stop=e.data[i+1].x
                                else stop=start

                                ctx.fillRect(start, chartArea.top, stop - start, chartArea.bottom - chartArea.top);
                            }
                            }
                        }
                    }]

Upvotes: 1

Views: 71

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31351

This is because you are using the beforeDatasetsDraw callback, as you can see in this diagram chart.js draws the layers with a z index of 0 and lower first, since they are already drawn your box is drawn over it so if you change the callback from beforeDatasetsDraw to beforeDraw like so it should work:

plugins: [{
    id: '2',
    beforeDraw: function(chart: any, easing: any) {
        if (chart.chartArea) {
            var ctx = chart.ctx;
            var chartArea = chart.chartArea;
            let d = data.chart.relay;
            let e = chart.getDatasetMeta(0)
            ctx.fillStyle = '#b3ff99';

            var start!: number;
            var stop!: number;
            for (let i = 0; i < d.length; i++) {
                start = e.data[i].x
                if (d[i] && d[i + 1] === true) stop = e.data[i + 1].x
                else stop = start

                ctx.fillRect(start, chartArea.top, stop - start, chartArea.bottom - chartArea.top);
            }
        }
    }
}]

Another solution you can do is to first check if the rect is within the chart area, if it's left side will go out use the leftside of the chartArea instead so it will never get behind or over the y labels, same for right, top and bottom

Upvotes: 1

Related Questions