简体   繁体   中英

Customize fill colors for ChartJS 3.x using beforRender plugin event

I try to apply the code i can see in this question: https://github.com/chartjs/Chart.js/issues/3071

but i cant understand how to change code to make it works in chartJS v3.x

        this.ChartInst = new Chart(this._ctx, {
        type: "line",
        data: this._data ,
        options: this._chartoptions,
        plugins: [{
            beforeRender: function (c, args, options) {
                var gradientFill = c.ctx.createLinearGradient(0, 0, 0, c.height);
                gradientFill.addColorStop(0.4, 'rgba(223,140,255,0.25)');
                gradientFill.addColorStop(0.6, 'rgba(83, 155, 243, 0.25)');
                var model = c.data.datasets[0];
                
                model.backgroundColor = gradientFill;
                //console.log(model)
            }
        }]
    })

the event is called, and when i console.log the model var, i can see backgroundColor is set on CanvasGradient but nothing happen on chart. (Just default grey background)

Any idea? Thanks

After some search i found a solution changing the event of plugin to beforeDraw and calling the update() method of chart.

this.ChartInst = new Chart(this._ctx, {
        type: "line",
        data: this._data ,
        options: this._chartoptions,
        plugins: [{
            beforeDraw: function (c, a, o) {
                var yScale = c.scales['y'];                   
                var max = c.data.datasets[0].data.reduce(function (prev, current) { return (prev.y > current.y) ? prev : current }).y;
                var yPos = yScale.getPixelForValue(max);
                var gradientFill = c.ctx.createLinearGradient(0, yPos, 0, c.height);
                gradientFill.addColorStop(0.4, 'rgba(83, 155, 243, 0.25)');
                gradientFill.addColorStop(0.9, 'rgba(223,140,255,0.25)');
                c.data.datasets[0].backgroundColor = gradientFill;
                c.update();
            }
        }]
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM