2
votes

Comment enregistrer un canevas avec un canevas en blob sans fond noir?

J'essaie d'enregistrer un graphique à partir de charts.js, mais il est enregistré avec un arrière-plan noir et je ne sais pas comment changer cet arrière-plan en transparent ou blanc.

J'utilise Canvas to blob et FileSaver

Ceci est mon script

$("#download").click(function() {
        var canvas = document.getElementById("canvas");
        canvas.toBlob(function(blob) {
            saveAs(blob, "grafica.png");
        });
    });


0 commentaires

3 Réponses :


0
votes

Je ne connais pas la bibliothèque, mais avez-vous essayé de lui donner un fond blanc? Quelque chose comme ce qui suit? Il peut utiliser le noir par défaut lorsqu'aucune couleur n'est rencontrée à un pixel particulier.

$("#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");
    });
});


1 commentaires

ok il peint tout en blanc mais maintenant le graphique ne montre pas haha



0
votes

Je viens de dessiner un fond blanc avant de dessiner le graphique sur le script et de résoudre le problème du fond noir :)

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


0 commentaires

0
votes

Si vous ne voulez pas jouer avec le canevas du graphique lui-même, vous pouvez utiliser un toile hors écran et dessinez-y l'arrière-plan.

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


0 commentaires