Skip to main content
inespa
Participating Frequently
December 4, 2018
Answered

HTML5 Canvas - Download image from game

  • December 4, 2018
  • 1 reply
  • 1487 views

Hi

This is a follow up question to this post, now that I've had an oportunity to come back and improve on it - How do i save my game's ending as image?

I've been trying to find an alternative to "document.body.appendChild(image);" as means to save an image of the game I made - appending a link seems a bit low key, and may pass unnoticed (specially since the game is aimed at children).

Opening the image on a new tab/window using "window.open" won't work in Chrome, so that's useless as well - it would have been a great option!

I wonder if there is another way to do this.

- is there a way to trigger a "save image as" window so the user can do it?)

- or can i make this link appear inside the game attached to an object (maybe an image appears with "click here for image" so the user can right click to save...?)

- some other way people with more know how would know....

Thank you!

This topic has been closed for replies.
Correct answer kglad

var aTag = document.createElement('a');

aTag.setAttribute('href', canvas.toDataURL("image/png"));

aTag.download = "YourScreenshot.png";

this.btn.addEventListener('click',f.bind(this));

function f(){

aTag.click();

}

1 reply

kglad
Community Expert
December 5, 2018

you can use anything that involves user interaction to trigger aTag.click() without adding aTag to the display and without assigning any visible content to aTag.

inespa
inespaAuthor
Participating Frequently
December 5, 2018

Right, so I could trigger the save as "click" with the same function that creates the image.

But just «aTag.click()» won't work, and neither does «document.getElementById("a").click();» - maybe I'm missing something?

I'd be really grateful if you could help me with this

kglad
kgladCorrect answer
Community Expert
December 5, 2018

var aTag = document.createElement('a');

aTag.setAttribute('href', canvas.toDataURL("image/png"));

aTag.download = "YourScreenshot.png";

this.btn.addEventListener('click',f.bind(this));

function f(){

aTag.click();

}