0

I have a "save" button and I need it to allow the user to download the canvas image as a PNG or JPG file.

At the moment, I found this code:

$('#save').on("click",function(){
    var w=window.open('about:blank','image from canvas');
    w.document.write("<img src='"+canvas.toDataURL("image/png")+"' alt='from canvas'/>");
})

Which opens the canvas image into a new page, and allows the image to be downloaded (It shows the image as a black image otherwise). Is there a way in which when the user clicks the save button they download the image directly without clearing the current canvas or opening in a new page?

Nikhil Kinkar
  • 761
  • 8
  • 31
  • 1
    Maybe this [**JsFiddle Demo**](http://jsfiddle.net/wboykinm/fL0q2uce/) will be of some use to you. This is using a anchor tag, not a button as it uses the `href` in the download function. – NewToJS Oct 28 '17 at 06:51
  • @NewToJS I copied the fiddle code to my file and it's working almost exactly the way I want! There's one thing though - My background is transparent and the code is giving me a completely black background behind the canvas image - is there a way to fix this? – CaptainObvious Oct 28 '17 at 07:11
  • Have you tried replacing the `ctx.fillStyle` to `ctx.fillStyle = "rgba(0, 0, 0, 0)";` For example: [**JsFIddle Demo 2**](http://jsfiddle.net/0qt8saoj/) – NewToJS Oct 28 '17 at 07:50
  • I found the code for replacing the background from here: https://stackoverflow.com/questions/32160098/change-html-canvas-black-background-to-white-background-when-creating-jpg-image @NewToJS if you answer this question with what you wrote in your comment, I will pick it as the best answer. It helped a lot! – CaptainObvious Oct 28 '17 at 08:28

1 Answers1

1

setting the href and than using download attribute is an easy trick for downloading canvas images, but it doesn't work always and in all browsers, I would recommend you use FileSaver for saving canvas images.

  • Include the FileSaver either via CDN or locally as per your comfort.

  • further in your code use saveAs() (this is defined in FileSaver) as follows:

code :

$('#save').on("click", function() {  
  canvas.toBlob(function (blob) {  
    saveAs(blob, 'output.png');  
  }, 'image/png');
});

this will work out fine.

Nikhil Kinkar
  • 761
  • 8
  • 31