2016-03-07 168 views
0

我需要将在画布中创建的图表导出为图像文件。我设法做到了,但图像透明(无背景)。我的问题是,是否有代码的方式来添加背景颜色的现有图像,我从画布?将背景添加到透明图像

例子:

帆布浏览器: enter image description here

帆布当导出为巴纽:

enter image description here

+1

添加背景颜色到您的画布? – cmorrissey

+0

如何导出图像?任何可以测试的示例代码? – Rayon

+0

您是否在绘制图表之前尝试使用白色的画布填充[fillRect](http://www.w3schools.com/tags/canvas_fillrect.asp)?在cmmorrissey – bviale

回答

0

没有必要使用JavaScript,只是给图像背景使用CSS的颜色。

<style> 
    img { 
     background-color: black; 
    } 
</style> 
<img src="..."> 

另一个例子来看看这个的jsfiddle:https://jsfiddle.net/3jch7z94/1/

+0

您有一个很好的计划,可以在屏幕上显示背景图。但是,CSS背景在导出为图像文件后不会显示在画布上。为了显示背景颜色,必须将它们与图表一起绘制到画布元素上。 :-) – markE

+0

@markE他说他已经导出了他的画布,并且导出时有一个透明背景。如果问题不准确,并且图像实际上具有不透明的背景,那么显然这是行不通的。 – AmericanUmlaut

2

您有几种方式来完成你的任务。

到目前为止,最简单的方法是在开始绘制图表之前用整个画布填充背景颜色。 提示:你没有显示代码,但如果可能的话,做这个简单的解决方案。 ; =)

context.fillStyle='white'; 
context.fillRect(0,0,canvas.width,canvas.height) 

如果您不能在启动前填充,您仍然有一些选项。

您可以将图表另存为另一个画布,使用背景颜色填充整个主画布,然后将保存的图表重新绘制回主画布。

// 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'; 
+1

谢谢你这个描述性的答案! – MapleSyrup