Canvas.toDataURL () returns a file without extension

Im converts html canvas to jpg when save button is clicked. I am using the code below

$('#save').click(function(e){ var canvas = $('#myCanvas')[0]; var image = canvas.toDataURL("image/png").replace("image/png","image/octet-stream"); window.location.href=image; // it will save locally }); 

Unfortunately, I am uploading a file without any extension. I want, when I click the download button, the browser should download the file from the page with the file extension.

thanks

+6
source share
3 answers

Assuming your #save element is an anchor tag ( <a ...></a> ), you can do this:

 $('#save').click(function(e){ var canvas = $('#myCanvas')[0]; var image = canvas.toDataURL("image/png"); $('#save').attr({ 'download': 'myFilename.png', /// set filename 'href' : image /// set data-uri }); }); 

Ideally, you install href before clicking. Somehow.

+3
source

@ K3N answer did not work for me because, as already mentioned:

Ideally, you install href before clicking somehow.

I built on top of it and did it, and it works great.

 var btnSave = document.getElementById('btnSave'); btnSave.addEventListener('click', function() { var image = photo.toDataURL("image/png"); var anchor = document.createElement('a'); anchor.setAttribute('download', 'myFilename.png'); anchor.setAttribute('href', image); anchor.click(); }); 
+2
source

You should use:

 var canvas = document.getElementById("mycanvas"); var img = canvas.toDataURL("image/png"); 

To download you need to use:

 document.write('<img src="'+img+'"/>'); 
+1
source

All Articles