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

Viewed 1715

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");
        });
    });
3 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");
});

I'm not familiar with the library but have you tried actually giving it a white background? Something like the following? It might be using black a default when no color is encountered at a particular pixel.

$("#download").click(function() {
    var canvas = document.getElementById("canvas"),
        ctx = canvas.getContext("2d");

    ctx.fillStyle = "#ffffff";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    canvas.toBlob(function(blob) {
        saveAs(blob, "grafica.png");
    });
});

i just draw a white backgroung before draw the chart on the script and solve the black background problem :)

var backgroundColor = 'white';
Chart.plugins.register({
    beforeDraw: function(c) {
        var ctx = c.chart.ctx;
        ctx.fillStyle = backgroundColor;
        ctx.fillRect(0, 0, c.chart.width, c.chart.height);
    }
});
Related