The toDataURL function
The toDataURL function can be used to get a base64 encoded URL-safe representation of your canvas
The toDataURL function returns a data: URL representing the canvas at the time that the function is called. Using this function you can transfer the canvas to your server (using jquery for example) as a base64 encoded string and then use server-side scripting (eg PHP, ASP) to decode the string and save it to a file.
<script>
window.onload = function ()
{
var canvas = document.getElementById("cvs");
var context = canvas.getContext('2d');
// Note that the toDataURL function is on the canvas object - NOT the context.
// Transfer (using a HTTP POST request) the base64 encoded string to the server with jQuery
var image_data = canvas.toDataURL("image/png");
$.post("save_chart.php", { src: image_data } );
// Alternatively you could use the data: URL as the SRC of an image tag to show it on the page
}
</script>
And the php server-side code would be:
<?php
// You need to adjust this to suit
$filename = '/tmp/myChart.png';
$src = $_POST['src'];
$src = substr($src, strpos($src, ",") + 1);
$decoded = base64_decode($src);
$fp = fopen($filename,'wb');
fwrite($fp, $decoded);
fclose($fp);
?>
Arguments to the function
- [Optional] The content type required. Defaults to PNG
Note: If you're using the toDataURL function then any images that you draw on the canvas should be hosted on the same domain/server as the page. If they're not - an error occurs.