Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to trigger download of a image which was generated locally using canvas?

How to trigger download of a image which was generated locally in canvas?

I have got no idea how to start solving this problem.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Convert it into a dataUrl and create the element. Take a look to this snippet of code:

let download = function(){
  var finalUrl = document.createElement('a');
  finalUrl.download = 'my-beautiful-canvas.png';
  finalUrl.href = document.getElementById('canvas').toDataURL()
  finalUrl.click();
}

The logic is this:

  • Create a new anchor element
  • Setting up some things, like download name
  • Selecting the url using the document.get… method. There you can put even id, classes or what you want. It’s useful if you have multiple canvas and you want to select only one of these. You get the data URL of the canvas itself.
  • Simulate a click. Since is an anchor tag with the download attribute, you’ll be prompted to the download.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading