Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a Canvas with canvas to blob without black background?

I am trying to save a chart from charts.js but its save with a black background and don´t know how to change that background to transparent or white.

I am using Canvas to blob and FileSaver

This is my script

$("#download").click(function() {
        var canvas = document.getElementById("canvas");
        canvas.toBlob(function(blob) {
            saveAs(blob, "grafica.png");
        });
    });
like image 832
LuisCas Avatar asked Oct 22 '25 01:10

LuisCas


1 Answers

If you don't want to mess with the chart's canvas itself, you can use an offscreen canvas and draw the background there.

const canvasWithBackground = document.createElement('canvas');
canvasWithBackground.width = canvas.width;
canvasWithBackground.height = canvas.height;

const ctx = canvasWithBackground.getContext('2d')!;
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(canvas, 0, 0);

canvasWithBackground.toBlob(function(blob) {
    saveAs(blob, "grafica.png");
});
like image 145
Josh Kelley Avatar answered Oct 24 '25 16:10

Josh Kelley