我需要将在 Canvas 中创建的图表导出为图像文件。我设法做到了,但图像是透明的(没有背景)。我的问题是,有没有一种方法可以使用代码为我从 Canvas 获得的现有图像添加背景颜色?
例子:
导出为 .png 时的 Canvas :
最佳答案
您可以通过多种方式完成任务。
到目前为止,最简单的方法是在开始绘制图表之前用背景色填充整个 Canvas 。 提示:您不显示代码,但如果可能,请执行此简单的解决方案。 ;=)
context.fillStyle='white';
context.fillRect(0,0,canvas.width,canvas.height)
如果您无法在开始前填写,您仍然有一些选择。
您可以将图表保存到另一个 Canvas ,用背景颜色填充整个主 Canvas ,然后将保存的图表重新绘制回主 Canvas 。
// create a second canvas and draw the chart onto it
var secondCanvas=document.createElement('canvas');
var cctx=secondCanvas.getContext('2d');
secondCanvas.width=canvas.width;
secondCanvas.height=canvas.height;
cctx.drawImage(mainCanvas,0,0);
// fill the main canvas with a background
context.fillStyle='white';
context.fillRect(0,0,canvas.width,canvas.height)
// redraw the saved chart back to the main canvas
context.drawImage(secondCanvas,0,0);
您可以使用合成在现有像素后面绘制新绘图。绘制整个背景,它将出现在现有图表的后面。
// set compositing to draw all new pixels (background) UNDER
// the existing chart pixels
context.globalCompositeOperation='destination-over';
// fill the main canvas with a background
context.fillStyle='white';
context.fillRect(0,0,canvas.width,canvas.height)
// always clean up ... reset compositing to default
context.globalCompositeOperation='source-over';
关于javascript - 为透明图像添加背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35849573/