Change the background color of generated image
Closed this issue · 2 comments
Hi,
I want to change the background color of the generated chart image.
With code like this:
chartNode.on('beforeDraw', function(ChartJs) {
var ctx = ChartJs.Chart.ctx;
ctx.fillStyle = "white";
ctx.fillRect(0, 0, ChartJs.chart.width, ChartJs.chart.height);
});
However, I did not manage to access the ctx
, from the provided ChartJs.
Can it be accessed? Or is there any other way to change the background color?
Regards,
Thomas
Hi,
I'm using the following code to set the background color:
ChartJS.plugins.register({
beforeDraw: function(chartInstance) {
var ctx = chartInstance.chart.ctx;
ctx.fillStyle = "white";
ctx.fillRect(0, 0, chartInstance.chart.width, chartInstance.chart.height);
}
});
I have a server running chartjs-node that returns charts. I'm using the code above to set the background colour, but after it has been set once in the server's lifetime, the colour remains. I have a controller where basically the following happens:
const chart = new ChartjsNode(width, height);
const config = {};
// some logic here processes request args and fills config
// most notably resulting in config.options.plugins.beforeDraw being set to:
function (instance) {
const ctx = instance.chart.ctx;
ctx.fillStyle = params.backgroundColor ? params.backgroundColor : transparent;
ctx.fillRect(0, 0, instance.chart.width, instance.chart.height);
}
// then...
await chart.drawChart(configuration);
Where params.backgroundColor
is an RGBA string from request, and transparent
is an RGBA string for white with full transparency.
After server launch, it will be transparent if no colour is requested. Request a colour, and it works. However, if you remove the colour, it gets 'stuck'.
If I change transparent
to solid white, it goes back white, but adding multiple statements to first set to solid white, then transparent white, still results in it coming back the colour from the last request that specified backgroundColor
.