8

I'm converting an HTML canvas into a jpg when a save button is clicked. I use 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 download file without any extension. What I want is when I click the download button, The browser must download file from the page with a file extension.

Thanks

Amir
  • 1,328
  • 2
  • 13
  • 27
Emmanuel Gabion
  • 425
  • 1
  • 9
  • 20

3 Answers3

3

@K3N's answer didn't work for me because as mentioned:

Ideally you set the href before the click somehow.

I built on top of it and did this 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();
});
beon
  • 493
  • 1
  • 4
  • 12
2

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 set the href before the click somehow.

1

You should use:

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

for loading,you need to use:

document.write('<img src="'+img+'"/>');
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125