How to trigger download of a image which was generated locally in canvas?
I have got no idea how to start solving this problem.
Advertisement
Answer
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.