A few years ago, when HTML5 was not yet popular, our project manager once asked me such a requirement: let project review experts use a pen to electronically sign on a tablet computer at the end of the review.
This requires our review software to provide such a function: open the browser, log in, and enter the review page. There is a square area at the bottom of the page, where the user signs with a touch pen, and then the signature will be kept on the server.
Such a requirement took me a lot of trouble at the time, but now that I think about it, it is really easy to implement it with html5 canvas. In the article "How to save the canvas (canvas) image as a local picture", there is a sketchpad function implemented with only a few lines of code-very simple, although there is a small bug-but it can be used as For signature.
I have talked a lot about how to save the canvas image as a picture and download it, but these methods are to save the picture to the client, and our signature requirement is to save the content of the canvas to the server, how to achieve it?
In fact, it is very simple. After reading the following PHP code, I believe you will also find it very simple.
<?php
// requires php5
define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
The picture uploaded from the webpage to the server is in the Data URL format transcoded by base64_encode, and the data is decoded by base64_decode on the server and saved as a file.
One day you will need to use it, very useful code, bookmark it!