How to Save an HTML5 Canvas as an Image on a Server
In your quest to allow users to save images generated from an HTML5 canvas, you encountered difficulties. To resolve this, here's an improved approach:
JavaScript Code:
function saveImage() { var canvasData = canvas.toDataURL("image/png"); var formData = new FormData(); formData.append("canvasData", canvasData); var ajax = new XMLHttpRequest(); ajax.open("POST", "save-image.php", false); ajax.onreadystatechange = function() { console.log(ajax.responseText); }; ajax.send(formData); }
PHP Code (save-image.php):
if (isset($_POST["canvasData"])) { $data = $_POST["canvasData"]; $uri = substr($data, strpos($data, ",") + 1); $fp = fopen('/path/to/file.png', 'wb'); fwrite($fp, base64_decode($uri)); fclose($fp); }
Breakdown:
Tips:
The above is the detailed content of How to Save an HTML5 Canvas Image to a Server Using JavaScript and PHP?. For more information, please follow other related articles on the PHP Chinese website!