Saving an HTML5 Canvas as an Image on a Server
To save an HTML5 canvas as an image on a server, follow these steps:
1. Convert the Canvas to an Image Data URL
var canvasData = canvas.toDataURL("image/png");
2. Create an XMLHttpRequest Object
var ajax = new XMLHttpRequest();
3. Open a POST Request and Set Request Header
ajax.open("POST", "testSave.php", false); ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
4. Send Canvas Data
ajax.send("imgData=" + canvasData);
5. Handle Response
ajax.onreadystatechange = function() { console.log(ajax.responseText); }
6. On PHP Server
Receive the canvas data and write it to the server as a PNG file:
<?php if (!empty($_POST['imgData'])) { // Convert base64 data to raw data $imgData = base64_decode($_POST['imgData']); // Set path and open file $fp = fopen('/path/to/file.png', 'wb'); // Write raw data to file and close fwrite($fp, $imgData); fclose($fp); } ?>
Additional Notes:
The above is the detailed content of How Can I Save an HTML5 Canvas as an Image on a Server?. For more information, please follow other related articles on the PHP Chinese website!