Javascript download superposed images with transparent opacity

Viewed 48

Let's say I have a div containing multiple images superposed with opacity between 0 and 100%. By exemple:

.imgsParent{
position: relative;
width: 300px;
height: 300px;
}

.imgsParent img{
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
opacity: 50%
}
<div class="imgsParent">
  <img style="background-color:blue"/>
  <img style="background-color:red"/>
</div>

If I want a button to download the final visible image, how do I make that possible?

Thank you!

1 Answers

I finally made it work using the library html2canvas.

Here is the code for my button:

function downloadImg() {
  html2canvas(document.querySelector("#imgsContainer") as HTMLElement).then(
    (canvas) => {
      downloadCanvas(canvas, "generatedImage.png")
    }
  );
}

//ref: https://codepen.io/joseluisq/pen/mnkLu
function downloadCanvas(canvas: HTMLCanvasElement, filename: string) {
  /// create an "off-screen" anchor tag
  var lnk = document.createElement('a'),
    e;

  /// the key here is to set the download attribute of the a tag
  lnk.download = filename;

  /// convert canvas content to data-uri for link. When download
  /// attribute is set the content pointed to by link will be
  /// pushed as "download" in HTML5 capable browsers
  lnk.href = canvas.toDataURL("image/png;base64");

  /// create a "fake" click-event to trigger the download
  if (document.createEvent) {
    e = document.createEvent("MouseEvents");
    e.initMouseEvent("click", true, true, window,
      0, 0, 0, 0, 0, false, false, false,
      false, 0, null);

    lnk.dispatchEvent(e);
  } else {
    lnk.click();
  }
}
<button className='downloadImg' onClick={downloadImg}> Download Image </button>

Related