canvas输出图片码流时候设置背景色

问题

先前在项目中用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;
}

主要几个步骤

  1. 从canvas中得到ImageData
  2. 将globalCompositeOperation属性设置为destination-over. 然后将会在当前图形之下绘制新的图形
  3. 画一个rectangle填充你想要的背景色
  4. 此时再生成码流
  5. 后面就是清除canvas恢复到最初状态即可

参考资料

  1. 解决方案
  2. MDN
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,909评论 25 708
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,192评论 4 61
  • 我要开始减肥了,为了在灵魂想要一场说走就走的旅行时,肉体不会成为阻碍。
    晴天红阅读 262评论 0 0
  • 总是,默默无言 无数次鼓起的唇 在空中尴尬的停滞 真的不知道如何收场 人之间的距离其实很隐含 在时光的河中 我们都...
    yahqq阅读 286评论 1 0
  • Cite: http://adv-r.had.co.nz/Data-structures.html R's bas...
    43daf5f8181f阅读 349评论 0 0