jQuery: Send HTML5 Canvas to Server via Ajax
Tutorial by Stefan Trost | 2016-10-23 at 16:11
In this tutorial, I want to show you how to send an HTML5 canvas via Ajax to a PHP script on your server in order to receive and save the canvas there as an image using JavaScript and jQuery.
First, I will explain all individual paths of the procedure, at the end of this tutorial, you will find both files we use in full length. This tutorial is sending the canvas with the help of Ajax and jQuery to the server and therefore is coming along without any form or reloading the page. I have written another tutorial, which is explaining how to send an HTML 5 canvas together with a form. This tutorial describes how to attach the canvas image to an existing form. Depending on what you are rather interested in, you should read that or this tutorial.
The HTML-Page
For our example, we are getting along with relatively little HTML. Actually, we only need our canvas and a button.
<canvas id="canv" width="200" height="200"></canvas> <button id="bt_upload">Upload</button>
With clicking the button, the canvas should be sent to our script later.
Draw Canvas
For demonstration, the content of our canvas does not matter. However, that we do not have to store an empty canvas, we are just drawing a red circle in the middle of it. That is done by the following code for us.
var canvas = document.getElementById('canv'); var context = canvas.getContext('2d'); context.arc(100, 100, 50, 0, 2 * Math.PI); context.lineWidth = 5; context.fillStyle = '#EE1111'; context.fill(); context.strokeStyle = '#CC0000'; context.stroke();
Who wants to learn more about drawing on a canvas, should have a look at the HTML5 Canvas Tutorial for beginners.
JavaScript for Sending
The interesting part of this tutorial is coming now. In the following, we can see the jQuery code which is responsible for sending the canvas to our PHP script.
Because the sending should be initialized by clicking our button (which has the ID bt_upload in the HTML), first, we are defining a .click() function for it.
Within this function, we are starting with fetching our canvas and using the function toDataURL(). This function provides us with a base64 encoded string representation of the canvas content in the form "data:image/png;base64;iVBORw0KGgoA...". We need this kind of representation to be able to transfer the data with our script.
$(document).ready(function() { $("#bt_upload").click(function() { var canvas = document.getElementById('canv'); var dataURL = canvas.toDataURL(); $.ajax({ type: "POST", url: "canvas_ajax_upload_post.php", data: { img: dataURL } }).done(function(msg){ alert(msg); }); }); });
Subsequently, we are using jQuerys' $.ajax() in order to send the data. In our example, we have stored the script under the name "canvas_ajax_upload_post.php", but of course, you can also use any other name you want. We will get the answer of the script in the variable "msg" which we will then just display by means of a simple dialog. In a real world application, perhaps, it would be better to set this as the content of a DIV container for showing the message inline.
PHP-Script for Receiving
Now we are coming to the PHP script that is stored on our server under the name "canvas_ajax_upload_post.php". This script should save our image we have sent. In the JavaScript for sending the data, we used type: "POST" and data: { img: dataURL }. Therefore, we can now pick up our prepared dataURL with $_POST['img'] now. Of course, it is your decision whether you will name those variables img and dataURL or if you rather want to take any other name.
Furthermore, we wrote canvas.toDataURL() in the JavaScript which should deliver the image in PNG format by default. That is why the passed string should always start with "data:image/png;base64;". We are checking this in our first if condition and we will only proceed if the format is indeed PNG.
<?php $img = $_POST['img']; if (strpos($img, 'data:image/png;base64') === 0) { $img = str_replace('data:image/png;base64,', '', $img); $img = str_replace(' ', '+', $img); $data = base64_decode($img); $file = 'uploads/img'.date("YmdHis").'.png'; if (file_put_contents($file, $data)) { echo "The canvas was saved as $file."; } else { echo 'The canvas could not be saved.'; } } ?>
However, before we can save the image, we have to undo the base64 encoding again. First of all, we do not need the "data:image/png;base64;" anymore and we are deleting this part from the string. Then, we have to replace each space with a + before we can use the function base64_decode() for getting the raw data back.
Now, we only need to save this data and we are finished. As filename, we are using 'uploads/img'.date("YmdHis").'.png' here. That means, that the folder "uploads" must exist on our server and each image is saved under the current date. Depending on whether the storage was successful or not, we are outputting some result text with echo. This is the text we receive in the variable msg within the JavaScript in order to show it in the alert that.
The full HTML-File
That was all. Here is the complete HTML file composed of the individual code snippets from above. You can save this file for example as something like "canvas_ajax_upload.php".
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.js"></script> </head><body> <canvas id="canv" width="200" height="200"></canvas> <button id="bt_upload">Upload</button> <script> var canvas = document.getElementById('canv'); var context = canvas.getContext('2d'); context.arc(100, 100, 50, 0, 2 * Math.PI); context.lineWidth = 5; context.fillStyle = '#EE1111'; context.fill(); context.strokeStyle = '#CC0000'; context.stroke(); $(document).ready(function() { $("#bt_upload").click(function() { var canvas = document.getElementById('canv'); var dataURL = canvas.toDataURL(); $.ajax({ type: "POST", url: "canvas_ajax_upload_post.php", data: { img: dataURL } }).done(function(msg){ alert(msg); }); }); }); </script> </body></html>
Apart from that file, additionally the PHP script for receiving and storing the image is necessary. The PHP script from above can be saved under the name "canvas_ajax_upload_post.php" in the same directory.
About the Author
You can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile
Related Topics
How to resize Image before Upload in Browser
Tutorial | 13 Comments
Send HTML5 Canvas as Image to Server
Tutorial | 0 Comments
HTML5 Canvas: Beginner Tutorial Chapter 1 - Introduction and Basics
Tutorial | 0 Comments
HTML5: Upload Images with Client Side Resize
Tutorial | 9 Comments
HTML5 Canvas: Beginner Tutorial Chapter 3 - Rectangles and Circles
Tutorial | 0 Comments
HTML5 Canvas: Beginner Tutorial Chapter 2 - Drawing Lines
Tutorial | 0 Comments
HTML5 Canvas: Beginner Tutorial Chapter 4 - Write Text on Canvas
Tutorial | 0 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.