Screenshot direct download

Hello everyone,

I would like the user to have the ability to take a screenshot from the canvas as shown in this tutorial:

https://developer.playcanvas.com/en/tutorials/capturing-a-screenshot/

But have the image downloaded directly without open a new tab and without save manually the image, as in this other tutorial:

https://playcanvas.com/project/605131/overview/capturing-screenshot-from-camera

Is there a simple way to mix the two behaviors?

Hey @J.Gic, this is probably better done using html2canvas.js and canvas2image.js libraries as shown here. This does exactly what you need, clicking the button results in the screenshot downloading without a new tab being opened.

2 Likes

Thanks DevilZ I found some problems in importing canvas2image.js but I found this Download function that does exactly what I was looking for.

var canvas = this.app.graphicsDevice.canvas;

// Start file download.
download(canvas,"screen.png");

function download(canvas, filename) {
  /// 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 if (lnk.fireEvent) {
    lnk.fireEvent("onclick");
  }
}

3 Likes