HTML 5 Canvas: Saving to a File with PHP

So you’ve finally discovered the wonder that is the HTML5 Canvas element. Great! If you’re like me, the first thing I wanted to do with it was doodle on it. I eventually worked out how to map touch/mouse events to the canvas and draw lines, but I wanted to save my creations!

As it turns out, the Canvas element has a method called toDataURL(), which base64 encodes the entire Canvas element and returns it as a string. From there, you can just pump it over to a server and handle it from there. Here’s the step-by-step, which assumes you are also running jQuery on your site.

Step 1: Save the canvas and POST the data

var data = document.getElementById("myCanvasID").toDataURL();
$.post("process.php", {
	imageData : data
}, function(data) {
	window.location = data;

Step 2: Process the POST data, and save it to a file.

$data = substr($_POST['imageData'], strpos($_POST['imageData'], ",") + 1);
$decodedData = base64_decode($data);
$fp = fopen("canvas.png", 'wb');
fwrite($fp, $decodedData);
echo "/canvas.png";

Note: The first line of this script removes the header information that is sent with the encoded data.

Thats all there is to it. You can now easily save your HTML 5 awesomeness.

Author: Jack Slingerland

I'm a software engineer working and living in Raleigh, NC. I work in Python, Django, Node.js, React+Flux, AngularJS, and PHP. I like to work out with Kettlebells, run, and spend my free time with my wife, cat, and dog.

15 thoughts on “HTML 5 Canvas: Saving to a File with PHP”

  1. fwrite and fclose are functions so leave the initial $ and everything works fine …

  2. Is this outdated? Because searching for the position of ” ,” doesn’t work for me because of the space before the comma.

    My data URLs look like “data:image/jpeg;base64,/9j/4AAQSkZJRg …”

    And they look like that for both FF and Chrome. So changing the code to look for “,” fixed it.

  3. Hi, thanks for the great post. I used images instead of drawing things and when I try to save the canvas, it only saves the empty canvas and doesn’t include the images! Do you have any solution for that? Thanks in advance!

    1. its probably because you didn’t use, image onload function, i.e wait until the javascript loads the image before you draw it.

  4. I m getting this error while saving the image… please help
    SecurityError: The operation is insecure.
    [Break On This Error]

    var data = document.getElementById(“canvasID”).toDataURL();

  5. But this .toDataURL(); will save the canvas data as an image and not a raw code. That means user can’t redraw the canvas in future. Is there any way where I can save the canvas data in raw mode, so that in future I can again re-edit the canvas?

  6. It does not work for me unfortunately. The images are stored but can not be shown again. The following error message (image can not be displayed, because it contains errors.)

Comments are closed.