Home >Web Front-end >JS Tutorial >How to Save an HTML5 Canvas Image to a Server?
Generative art projects often require the ability to save the created images to the server. Here are the steps involved:
JavaScript Code:
function saveImage() { var canvasData = canvas.toDataURL("image/png"); var ajax = new XMLHttpRequest(); ajax.open("POST", "testSave.php", false); ajax.onreadystatechange = function() { console.log(ajax.responseText); } ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajax.send("imgData=" + canvasData); }
PHP (testSave.php):
<?php $data = $_POST['imgData']; $file = "/path/to/file.png"; $uri = substr($data,strpos($data, ",") + 1); file_put_contents($file, base64_decode($uri)); echo $file; ?>
Common Issues:
Additional Tips:
The above is the detailed content of How to Save an HTML5 Canvas Image to a Server?. For more information, please follow other related articles on the PHP Chinese website!