Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save HTML 5 canvas to a file in Chrome?

Save PNG (etc.) work in this demo in Firefox, but not Chrome.

Convert to PNG (etc.) work in Firefox and Chrome.

Is there a way *in Chrome* to save an image of a canvas element to a local file -- or to a server?

like image 294
Sam Dutton Avatar asked May 22 '10 16:05

Sam Dutton


People also ask

How do I save a canvas in HTML?

To save the canvas drawing as an image, we can set the source of an image object to the image data URL. From there, a user can right click on the image to save it to their local computer. Alternatively, we could also open up a new browser window with the image data url directly and the user could save it from there.

Is canvas supported in HTML5?

Browser SupportThe latest versions of Firefox, Safari, Chrome and Opera all support for HTML5 Canvas but IE8 does not support canvas natively.


2 Answers

The simplest way to do it is to use the toDataURL() function.

Say you have a canvas:

var canvas =  document.getElementById("myCanvas");

Then, with a button with id "saveButton", you can make it pop open a new window with the canvas as a png, and the user can save that page.

document.getElementById("saveButton").onClick = function() {
    window.open(canvas.toDataURL());
}
like image 99
Timothy Armstrong Avatar answered Sep 19 '22 13:09

Timothy Armstrong


Sam Dutton: (regarding comment left in Timothy Armstrong's answer) The 'SECURITY_ERR: DOM Exception 18' error that you're getting is probably because in your Canvas you've loaded an image that comes from a different domain, eg. maybe the image is hosted on your server hence why you see the error locally but not when hosted on your server. Whenever you load images from a foreign domain into a Canvas, certain API calls are banned for security reasons such as toDataUrl() and getPixelData(). It's similar to the same origin policy issue you see with cross-domain Ajax calls.

As for SaveAs Canvas, browser implementation is spotty, for browsers that don't support it, I believe you can still have the canvas appear as an image inside an <img /> tag. Just set the src attribute to the data you get back from toDataUrl(), then you can invite the user to right click -> save as. I believe the demo in the link you posted does this.

like image 24
Sunday Ironfoot Avatar answered Sep 19 '22 13:09

Sunday Ironfoot