59 Votes

Send HTML5 Canvas as Image to Server

Tutorial by Stefan Trost | Last update on 2021-05-10 | Created on 2016-10-22

In this tutorial, I want to show you how to use a usual HTML form for sending an HTML 5 canvas as image together with all other form data to the server and save it there.

At the end of this tutorial, you will find the full HTML page without explanations. However, first I want to explain the procedure step-by-step. This tutorial comes without Ajax and jQuery. If you are interested in sending the canvas to your server without form and without a page reload using ajax, you can have a look at the tutorial in which I have explained how to send an HTML5 canvas using ajax to the server. Apart from that, this tutorial is constructed in a similar way.

The HTML-Page

We only need two elements for our HTML page. First, we need the canvas, secondly, we need the form. For our example, we will use a canvas with a size of 200 x 200 pixels.

<canvas id="canv" width="200" height="200"></canvas>

<form method="post" action="" onsubmit="prepareImg();">
  <input id="inp_img" name="img" type="hidden" value="">
  <input id="bt_upload" type="submit" value="Upload">
</form>

The form contains a submit button and a hidden field. Before submitting the form, we want to write the image data of our canvas into this hidden field, so that the data can be sent together with the form. This will be done by the function prepareImg(), which will be called automatically before the submit by means of onsubmit="prepareImg();". You will find an explanation of this function below.

Of course, we can also add arbitrary other input fields and form elements to our form (which would then be sent together with the image), but at this point we want to concentrate on the essential.

The Canvas

For our example, an empty image would be enough, but because it is better to see something, we are drawing a simple red circle onto our canvas.

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

I do not want to explain how to write on an HTML5 canvas at this point, because there is too much to explain. Therefore, I want to refer to the HTML 5 canvas beginner tutorial in which you can find a step-by-step explanation of how to draw and paint on a canvas.

The JavaScript

Above, we have already heard about the JavaScript function prepareImg() that is automatically called as soon as someone is taking on the submit button. Now, we want to have a look at this function.

function prepareImg() {
   var canvas = document.getElementById('canv');
   document.getElementById('inp_img').value = canvas.toDataURL();
}
  

First, we are getting the canvas, then we are using the function .toDataURL(). This function is converting the image data of the canvas to a base64 encoded string, but it can be dispatched via the form without any problems. The string contains the data in PNG format and starts something like that: "data:image/png;base64;iVBORw0KGgoA...".

With document.getElementById('inp_img').value we are writing said string into the hidden field of our form, so that the image data will be automatically sent when submitting the form.

PHP-Script for Receiving

Finally, we only need the PHP script that is able to receive the sent form data and that can store the canvas as image for us.

$img = $_POST['img'];
$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 "<p>The canvas was saved as $file.</p>";
} else {
   echo "<p>The canvas could not be saved.</p>";
}	

We can find our image in $_POST['img'], because of the hidden field is named "img". However, before being able to save the raw data as image, first, we have to undo the base64 encoding. For that, first, we have to remove the "data:image/png;base64," from the string and each space has to be replaced by a plus sign. After that, we can use the function base64_decode() for getting the data that we can store.

For saving, we are using the variable $file as filename. The storage is done in the folder "uploads" and we are using the current date as file name. If the storage was successful, we are displaying an appropriate message, an error otherwise.

The entire File

We are already finished. Because no one has to copy together all individual parts described in this tutorial, here I have the full HTML page with all used PHP and JavaScript codes for you.

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head><body>

<?php

if (count($_POST) && (strpos($_POST['img'], 'data:image/png;base64') === 0)) {
	
  $img = $_POST['img'];
  $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 "<p>The canvas was saved as $file.</p>";
  } else {
     echo "<p>The canvas could not be saved.</p>";
  }	
  
}
					 
?>

<canvas id="canv" width="200" height="200"></canvas>

<form method="post" action="" onsubmit="prepareImg();">
  <input id="inp_img" name="img" type="hidden" value="">
  <input id="bt_upload" type="submit" value="Upload">
</form>



<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();
	
	
  function prepareImg() {
     var canvas = document.getElementById('canv');
     document.getElementById('inp_img').value = canvas.toDataURL();
  }
  
</script>

</body></html>

You can save this file under the name "canvas_form_upload.php", for example, but of course, you can also use any other arbitrary name for it.

ReplyPositiveNegative

About the Author

AvatarYou 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

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.