4

I have the following code to save what is on the canvas to a file, but when it saves it saves as download as the file name. What can I do to use a custom filename instead of download?

// Get the Canvas
var ctx = document.getElementById("myChart").getContext("2d");

// Handle Saving the Canvas
$(document).on("click", "#save-graph", function(e){
    e.preventDefault();
    var image = ctx.canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
    window.location.href = image;
});
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

2 Answers2

4

You can follow this: http://eligrey.com/demos/FileSaver.js/

how to save canvas as png image?

Community
  • 1
  • 1
HoangHieu
  • 2,802
  • 3
  • 28
  • 44
0

You can use a link for that purporse with the atribute download like this:

<a id="save-graph" href="" download="custom_name.png">

And on clicking that link everything will stay the same, just change href attribute of the link and trigger click:

$(document).on("click", "#save-graph", function(e){
    e.preventDefault();
    var image = ctx.canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
    $("#save-graph").attr("href", image);
    $('#save-graph')[0].click();
});
Glance
  • 91
  • 1
  • 2