我正在尝试从Charts.js中保存图表,但是其保存背景为黑色,并且不知道如何将背景更改为透明或白色。
我正在使用Canvas to blob和FileSaver
这是我的剧本
$("#download").click(function() {
var canvas = document.getElementById("canvas");
canvas.toBlob(function(blob) {
saveAs(blob, "grafica.png");
});
});
答案 0 :(得分:0)
我对图书馆不熟悉,但是您是否尝试过给它一个白色背景?类似于以下内容?当在特定像素上没有遇到颜色时,可能默认使用黑色。
$("#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 :(得分:0)
在脚本上绘制图表并解决黑色背景问题之前,我只是先绘制一个白色背景,:
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);
}
});
答案 2 :(得分:0)
如果您不想弄乱图表的画布本身,可以使用offscreen canvas并在那里绘制背景。
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");
});