搜尋

首頁  >  問答  >  主體

如何從多個畫布匯出 jpg

我有多個畫布,這些畫布用作圖層。

canvas c1 = background image.
canvas c2 = charactor image.
canvas c3 = item image.

我的原始碼如下。

在同一位置設定三個畫布。

<div canvas="canvas-wrap">
<canvas class="canvas" id="c1">
<canvas class="canvas" id="c2">
<canvas class="canvas" id="c3">
</div>

.canvas-wrap{
  width: 600px;
  height:500px;
  max-width: 100%;
  position: relative;
  padding: 0;
  box-sizing: content-box;
}
.canvas{
  position: absolute;
  left:0;
  top:0;
  border: 0;
  max-width:100%;
  box-sizing: content-box;
  padding: 0;
  margin: 0;
}

現在,我想將這些畫布匯出為一張 jpg。

我有可以匯出一張畫布的原始碼,但我想從三張畫布中匯出一張jpg。

function saveCanvas(canvas_id)
{
    var canvas = document.getElementById("c1");
    var a = document.createElement('a');
    a.href = canvas.toDataURL('image/jpeg', 0.85);
    a.download = 'download.jpg';
    a.click();
}

P粉301523298P粉301523298258 天前528

全部回覆(1)我來回復

  • P粉166779363

    P粉1667793632024-04-04 19:20:54

    這是可能的,但更好的方法是使用 1 個畫布並將所有內容繪製到那裡。

    在這裡,我們創建一個虛擬畫布,循環遍歷所有畫布以將資料繪製到其上,然後保存該畫布生成的圖像。

    //store all canvasses in array so we can loop through them later
    const canvasses = [];
    ['c1','c2','c3'].forEach(canvasId => {
      canvasses.push(document.getElementById(canvasId));
    });
    
    function save(){
      //create one canvas to draw everything to
      const canvas = document.createElement("canvas");
      canvas.width = canvasses[0].width;
      canvas.height = canvasses[0].height;
    
      //draw other canvases here
      const ctx = canvas.getContext('2d');
      canvasses.forEach(data => {
        ctx.drawImage(data, 0, 0);
      });
    
      //original saving code, using the fake canvas we created
      var a = document.createElement('a');
      a.href = canvas.toDataURL('image/jpeg', 0.85);
      a.download = 'download.jpg';
      a.click();
    }

    回覆
    0
  • 取消回覆