美文网首页
canvas输出图片码流时候设置背景色

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

作者: 瘦人假噜噜 | 来源:发表于2017-04-23 23:36 被阅读0次

    问题

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

    相关文章

      网友评论

          本文标题:canvas输出图片码流时候设置背景色

          本文链接:https://www.haomeiwen.com/subject/knkuzttx.html