HTML5 Canvas: toDataURL()

Jakob Jenkov
Last update: 2014-06-15

It is possible to grab the contents of an HTML5 canvas using the canvas toDataURL() function. Here is a code example of that is done:

var canvas  = document.getElementById("ex1");
var dataUrl = canvas.toDataURL();

The data returned from the toDataURL() function is a string that represents an encoded URL containing the grabbed graphical data. The string can be shown in a textarea element, like this:

var canvas  = document.getElementById("ex1");
var dataUrl = canvas.toDataURL();

document.getElementById("textArea").value = dataUrl;

It is also possible to show the grabbed data in a new window. Here is the code to do that:

var canvas  = document.getElementById("ex1");
var dataUrl = canvas.toDataURL();

window.open(dataUrl, "toDataURL() image", "width=600, height=200");

Below is an example of a canvas with some graphics on. Below the canvas are two buttons that enable you to grab the graphics drawn on the canvas and show it in the textarea below the buttons, or show it in a new window.


HTML5 Canvas not supported



Jakob Jenkov

Featured Videos




















Advertisements

High-Performance
Java Persistence
Close TOC

All Trails

Trail TOC

Page TOC

Previous

Next