簡體   English   中英

如何將帶有畫布的畫布保存為沒有黑色背景的 blob?

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

我正在嘗試從 charts.js 保存圖表,但它以黑色背景保存,並且不知道如何將該背景更改為透明或白色。

我正在使用Canvas 來 blobFileSaver

這是我的腳本

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

如果您不想弄亂圖表的畫布本身,您可以使用屏幕外畫布並在那里繪制背景。

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

我對圖書館不熟悉,但你有沒有試過給它一個白色的背景? 像下面這樣的? 當在特定像素處沒有遇到顏色時,它可能使用黑色作為默認值。

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

我只是畫了一個白色的背景,然后在腳本上繪制圖表並解決黑色背景問題:)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM