An example of the toDataURL() function

Written 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


[No canvas support]

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) because the base64 encoded string can be quite long and it may exceed the allowed length for URLs. 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;

The output

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:

Here is an example of fetching the URL with JavaScript:'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