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}.

How to Use JavaScript to Save Canvas Data in Chrome

In HTML5, there is a new tag <canvas>, which is used to draw graphics via JavaScript. In this tutorial, I would like to share how to draw images on canvas, and how to save the canvas data to local disk by clicking button.

Dynamsoft Barcode Reader SDK
Ads Powered by Dynamsoft

Draw Images on Canvas

To develop web application, I prefer using Aptana Studio which contains a built-in web server.

Now, let’s create a basic web project which includes only a default index.html file.

aptana studio

Open index.html and add a <img> tag in <body>.

<img src="dynamsoft_logo_black.png" id="img" width="73" height="73" alt="dynamsoft"/>

Below the image, add a <canvas>.

<canvas width="73" height="73" id="canvas">canvas</canvas>

Create a button to trigger click event.

<button type="button" onclick="saveImage()">save image</button>

Draw the canvas when the page is finished loading.

<script type="text/javascript">
			window.onload = function() {
				var canvas = document.getElementById("canvas");
				var ctx = canvas.getContext("2d");
				var img = document.getElementById("img");
				ctx.drawImage(img, 0, 0);
			}
</script>

Run the project to see what we have done so far.

 GUI

Save Canvas Data to Local Disk

Finally, we can use following code to popup a dialog for saving the canvas data.

var canvas = document.getElementById("canvas");
document.location.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");

Both Chrome and Firefox support the method, whereas they behave differently.

Chrome

Chrome

Firefox 

Firefox

The problem is that we cannot programmatically set the file name and type.

Fortunately, there is an alternative in Chrome.

var link = document.createElement('a');
link.download = "test.png";
link.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");;
link.click();

Full code:

<!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>Save Image</title>
	</head>
	<body>
		<h1>Save Image</h1>
		<img src="dynamsoft_logo_black.png" id="img" width="73" height="73" alt="dynamsoft"/>
		<canvas width="73" height="73" id="canvas">canvas</canvas>
		<script type="text/javascript">
			window.onload = function() {
				var canvas = document.getElementById("canvas");
				var ctx = canvas.getContext("2d");
				var img = document.getElementById("img");
				ctx.drawImage(img, 0, 0);
			}
		</script>

		<button type="button" onclick="saveImage()">save image</button>
		<script type="text/javascript">
			function saveImage() {
				var ua = window.navigator.userAgent;

				if (ua.indexOf("Chrome") > 0) {
					// save image without file type
					var canvas = document.getElementById("canvas");
					document.location.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");

					// save image as png
					var link = document.createElement('a');
    				link.download = "test.png";
    				link.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");;
    				link.click();
				}
				else {
					alert("Please use Chrome");
				}
			}
		</script>
	</body>
</html>

You can download the source code – SaveImage. If you have any questions, please feel free to contact me at {Desmond at Dynamsoft dot com}.