Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading Canvas element to an image

What are the different ways to save a canvas object?

In my research, I've found two approaches:

var data = canvas.toDataURL(); var prev = window.location.href; window.location.href = data.replace("image/png", "image/octet-stream"); window.location.href = prev; 

Another way is to take a snapshot.

Are there other ways to do this?

Is it possible to customize the download filename?

like image 313
dchhetri Avatar asked Nov 14 '11 18:11

dchhetri


People also ask

How do I convert a canvas object to an image?

function convertCanvasToImage() { let canvas = document. getElementById("canvas"); let image = new Image(); image. src = canvas. toDataURL(); return image; } let pnGImage = convertCanvasToImage(); document.

How do I save a canvas as a picture?

You can save a canvas to an image file by using the method canvas. toDataURL() , that returns the data URI for the canvas' image data. The method can take two optional parameters canvas.


2 Answers

Solution that requires NO BUTTON:

var download = function(){   var link = document.createElement('a');   link.download = 'filename.png';   link.href = document.getElementById('canvas').toDataURL()   link.click(); } 

Useful if you have other triggers for downloading, or triggers that you can't easily reference.

like image 140
Ulf Aslak Avatar answered Nov 07 '22 11:11

Ulf Aslak


The one way to save is exporting as an image... You already found this solution, and it's the best one i think ;)

    var canvas = document.getElementById("mycanvas");     var img    = canvas.toDataURL("image/png");     document.write('<img src="'+img+'"/>'); 

You can use different image types. Change the mimetype in this function:

    canvas.toDataURL("image/jpeg"); 

An other way to save canvas data (into a PDF) is using the wkhtmltopdf Library

Cheers. Frank

frankneff.ch / @frankneff

like image 23
frank_neff Avatar answered Nov 07 '22 11:11

frank_neff