An example of the toDataURL functionWritten by Richard Heyes, on 26th May 2013
A guide explaining how to use the toDataUrl function to get a base64 encoded representation of your canvas
One way you can transfer your canvas around is by using the toDataUrl function. This function takes a snapshot of the appearance of the canvas and returns it as a base64 encoded data: URL. You can then transfer it around as you would any other text - though you may want to avoid sending it as a GET parameter (ie in the URL) as the base64 encoded string can be quite long and it may exceed the allowed length for URLs. can be long For example:
var canvas = document.getElementById('cvs'); var context = canvas.getContext('2d'); context.font = '26pt Arial'; context.fillText('Some example text!', 10, 40); url = canvas.toDataURL(); document.getElementById("out").value = url;
Here is an example of the output of the function. Here it's shown in a textarea - though you can just as easily use it in a link as the URL.
This is an example of the resulting URL. As you can see it is quite large - and this is just a simple canvas URL.
And here is the resulting image:
window.open(document.getElementById('cvs').toDataURL(), 'new_window', 'width=310,height=30')
Or you could get the URL and then use it as the src of an image tag:
<img src="data:image/png;base64,iVBORw0KGgoAAAA ... ">
Notes about usage
Older versions of browsers (eg Internet Explorer 9) may not be able to directly display the data: URL. ie If you
take the URL and paste it into your address bar it may not display the image. Newer browsers will be able to
display the image though.
Another quirk is that older versions of Chrome displayed the image that the data: URL represented but did not
show the URL in the address bar as it was too long. Current versions of Chrome is able to handle it though.
The default type of the image URL is image/png. This can be the only image format that is available. Most browsers
do support image/jpeg or
image/webp though. If you choose to use image/jpeg then if the third argument is a number between 0.0
and 1.0 then it's used
as the image quality. Another type that may be supported is image/jpeg. Keep in mind that if you use image/jpeg
then because the JPG format doesn't support transparency you need to
clear the canvas to (for example) white first - otherwise the background color will be black and you might
not be able to see what you have drawn (because you were expecting a transparent/white color).
If the canvas has no width or height an empty data URL is returned ( data: )
The returned image is 96dpi.