问题
先前在项目中用d3画了树图等svg图形,然后需求是需要以png格式上传这个图片到服务器保存以供其他地方调用,可以先生成svg码流,然后在canvas上绘图,最后在利用canvas.toDataUrl()生成png码流,然后上传到服务器,但是上传后发现一个问题就是png码流生成的图片丢失了canvas的背景色,背景色变为了透明的。
问题原因
查询问题后在canvas草案中发现原因是:
For image types that do not support an alpha channel, the image must be composited onto a solid black background using the source-over operator, and the resulting image must be the one used to create the data: URL.
当你利用toDataUrl输出的码流生成图片时候,根据图片格式不同会是透明或者黑色。
解决方案
直接上代码:
//Returns contents of a canvas as a png based data url, with the specified
//background color
function canvasToImage(backgroundColor)
{
//cache height and width
var w = canvas.width;
var h = canvas.height;
var data;
if(backgroundColor)
{
//get the current ImageData for the canvas.
data = context.getImageData(0, 0, w, h);
//store the current globalCompositeOperation
var compositeOperation = context.globalCompositeOperation;
//set to draw behind current content
context.globalCompositeOperation = "destination-over";
//set background color
context.fillStyle = backgroundColor;
//draw background / rect on entire canvas
context.fillRect(0,0,w,h);
}
//get the image data from the canvas
var imageData = this.canvas.toDataURL("image/png");
if(backgroundColor)
{
//clear the canvas
context.clearRect (0,0,w,h);
//restore it with original / cached ImageData
context.putImageData(data, 0,0);
//reset the globalCompositeOperation to what it was
context.globalCompositeOperation = compositeOperation;
}
//return the Base64 encoded data url string
return imageData;
}
主要几个步骤
- 从canvas中得到ImageData
- 将globalCompositeOperation属性设置为destination-over. 然后将会在当前图形之下绘制新的图形
- 画一个rectangle填充你想要的背景色
- 此时再生成码流
- 后面就是清除canvas恢复到最初状态即可
网友评论