canvas輸出圖片碼流時候設(shè)置背景色

問題

先前在項目中用d3畫了樹圖等svg圖形,然后需求是需要以png格式上傳這個圖片到服務(wù)器保存以供其他地方調(diào)用,可以先生成svg碼流,然后在canvas上繪圖,最后在利用canvas.toDataUrl()生成png碼流,然后上傳到服務(wù)器,但是上傳后發(fā)現(xiàn)一個問題就是png碼流生成的圖片丟失了canvas的背景色,背景色變?yōu)榱送该鞯摹?/p>

問題原因

查詢問題后在canvas草案中發(fā)現(xiàn)原因是:

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.

當(dāng)你利用toDataUrl輸出的碼流生成圖片時候,根據(jù)圖片格式不同會是透明或者黑色。

解決方案

直接上代碼:

//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屬性設(shè)置為destination-over. 然后將會在當(dāng)前圖形之下繪制新的圖形
  3. 畫一個rectangle填充你想要的背景色
  4. 此時再生成碼流
  5. 后面就是清除canvas恢復(fù)到最初狀態(tài)即可

參考資料

  1. 解決方案
  2. MDN
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,361評論 25 708
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,753評論 4 61
  • 我要開始減肥了,為了在靈魂想要一場說走就走的旅行時,肉體不會成為阻礙。
    晴天紅閱讀 275評論 0 0
  • 總是,默默無言 無數(shù)次鼓起的唇 在空中尷尬的停滯 真的不知道如何收場 人之間的距離其實很隱含 在時光的河中 我們都...
    yahqq閱讀 356評論 1 0
  • Cite: http://adv-r.had.co.nz/Data-structures.html R's bas...
    43daf5f8181f閱讀 374評論 0 0

友情鏈接更多精彩內(nèi)容