Hi im trying to save save image of chart. Im using Angular12, Chart.js for drawing charts. When I download it with toDataUrl() background in image is checkered[ https://i.stack.imgur.com/WYmBf.png ]
here is my code in ts file
public barChartLabels: Label[] = ['Pon', 'Uto', 'Sri', 'Cet', 'Pet', 'Sub', 'Ned'];
public barChartType: ChartType = 'bar';
public barChartLegend = true;
public barChartPlugins = [];
public colors: Colors[] = [
{
backgroundColor:
'rgb(0, 102, 255)'
}
];
public barChartData: ChartDataSets[] = [
{ data: [], label: 'Series A' }
];
data1: Array<number> =[0, 0, 0, 0, 0, 0, 0]
Skini(){
//var image = document.getElementById("voznje")!.toBase64Image();
var canvas : any = document.getElementById("voznje");
var ctx = canvas.getContext("2d");
//var image = ctx.toDataURL("image/jpeg");
var dataURL = canvas.toDataURL("image/png", 1.0);
console.log(dataURL)
var link = document.createElement('a');
link.download = "my-chart.png";
link.href = dataURL;
link.click();
//window.open(dataURL);
//console.log("Link",dataURL)
}
and this is in html
<canvas id="voznje"
style="background-color: white"
baseChart
[datasets]="barChartData"
[labels]="barChartLabels"
[options]="barChartOptions"
[plugins]="barChartPlugins"
[legend]="barChartLegend"
[chartType]="barChartType"
[colors]="colors">
</canvas>
I would like to have normal backgound. Thank you in advance
Solved it. Code now looks like this. Like person in comment said i needed to give color to canvas background.
Skini(){
//var image = document.getElementById("voznje")!.toBase64Image();
var canvas : any = document.getElementById("voznje");
var ctx = canvas.getContext("2d");
//var image = ctx.toDataURL("image/jpeg");
ctx.globalCompositeOperation = 'destination-over'
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
var dataURL = canvas.toDataURL("image/png", 1.0);
//console.log(dataURL)
var link = document.createElement('a');
link.download = "my-chart.png";
link.href = dataURL;
link.click();
//window.open(dataURL);
//console.log("Link",dataURL)
}
This happens because it gets transformed to a PNG so it doesn't have a background, if you want to have a background for your chart you will need to use a custom plugin to draw a big white box over the canvas before chart.js renders with a custom plugin as described here: https://www.chartjs.org/docs/master/configuration/canvas-background.html