How to export jpg from multiple canvases
P粉301523298
P粉301523298 2024-04-03 21:02:43
0
1
468

I have multiple canvases which are used as layers.

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

My source code is as follows.

Set three canvases at the same location.

<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;
}

Now, I want to export these canvases as a jpg.

I have source code that can export one canvas, but I want to export one jpg from three canvases.

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粉301523298
P粉301523298

reply all(1)
P粉166779363

It is possible, but a better way is to use 1 canvas and draw everything there.

Here we create a virtual canvas, loop through all canvases to draw data onto it, and then save the image generated by that canvas.

//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();
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!