How to Upload HTML Canvas Data to PHP Server

Last time, I shared my experience about how to use JavaScript saving HTML canvas data to local disk in Chrome. In this tutorial, I would like to share how to save HTML canvas data to remote service with JavaScript and PHP.

Dynamsoft Barcode Reader SDK Ads Powered by Dynamsoft

Uploading canvas data is a little bit complicated comparing to file upload. If you want to learn how to upload a file, you can read the tutorial PHP File Upload.

Let’s get started to create a project, which includes two files upload.html and upload_data.php. In addition, you need to create a folder upload for receiving files.

upload.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>Upload Canvas Data to PHP Server</title>
	</head>
	<body>
		<h1>Upload Canvas Data to PHP Server</h1>
		<canvas width="80" height="80" id="canvas">canvas</canvas>
		<script type="text/javascript">
			window.onload = function() {
				var canvas = document.getElementById("canvas");
				var context = canvas.getContext("2d");
				context.rect(0, 0, 80, 80);
				context.fillStyle = 'yellow';
				context.fill();
			}
		</script>

		<div>
			<input type="button" onclick="uploadEx()" value="Upload" />
		</div>

		<form method="post" accept-charset="utf-8" name="form1">
			<input name="hidden_data" id='hidden_data' type="hidden"/>
		</form>

		<script>
			function uploadEx() {
				var canvas = document.getElementById("canvas");
				var dataURL = canvas.toDataURL("image/png");
				document.getElementById('hidden_data').value = dataURL;
				var fd = new FormData(document.forms["form1"]);

				var xhr = new XMLHttpRequest();
				xhr.open('POST', 'upload_data.php', true);

				xhr.upload.onprogress = function(e) {
					if (e.lengthComputable) {
						var percentComplete = (e.loaded / e.total) * 100;
						console.log(percentComplete + '% uploaded');
						alert('Succesfully uploaded');
					}
				};

				xhr.onload = function() {

				};
				xhr.send(fd);
			};
		</script>
	</body>
</html>
  • Create a canvas tag, and draw a rectangle on canvas when the whole page has been loaded.
  • Create a button for triggering uploading event.
  • Create a form with a hidden input tag, which is used to save the data URL.
  • Use XMLHttpRequest to asynchronously upload form data to PHP service.

upload_data.php:

<?php
$upload_dir = "upload/";
$img = $_POST['hidden_data'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . mktime() . ".png";
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>

Now deploy the whole project to a web server, such as nginx, Apache and so forth. Visit localhost:port/upload.html, click the button, and open the file folder to check whether the image is there.

Anything unclear? Please feel free to contact me at {desmond at Dynamsoft dot com}.