Categories
Other Programming PHP Programming

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);
fclose();
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.

By Jack Slingerland

Founder of Kernl.us. Working and living in Raleigh, NC. I manage teams of software engineers and work in Python, Django, TypeScript, Node.js, React+Redux, Angular, and PHP. I enjoy hanging out with my wife and kids, lifting weights, and PC gaming in my free time.

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

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

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.

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!

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

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();

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?

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.