您可以使用canvas.toDataURL 将您的画布艺术品保存为编码图像
然后您可以使用 AJAX 将该编码图像数据提交到您的服务器。
这是一些使用 jQuery+AJAX 将图像数据 POST 到服务器上的文件的代码。
按钮点击事件中的客户端:
// create a dataUrl from the canvas
var dataURL= canvas.toDataURL();
// post the dataUrl to php
$.ajax({
type: "POST",
url: "upload.php",
data: {image: dataURL}
}).done(function( respond ) {
// you will get back the temp file name
// or "Unable to save this image."
console.log(respond);
});
你没有提到你使用的是什么服务器,但是 PHP 是一个普通的服务器。
服务器文件:upload.php
<?php
// make sure the image-data exists and is not empty
// xampp is particularly sensitive to empty image-data
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) {
// get the dataURL
$dataURL = $_POST["image"];
// the dataURL has a prefix (mimetype+datatype)
// that we don't want, so strip that prefix off
$parts = explode(',', $dataURL);
$data = $parts[1];
// Decode base64 data, resulting in an image
$data = base64_decode($data);
// create a temporary unique file name
$file = UPLOAD_DIR . uniqid() . '.png';
// write the file to the upload directory
$success = file_put_contents($file, $data);
// return the temp file name (success)
// or return an error message just to frustrate the user (kidding!)
print $success ? $file : 'Unable to save this image.';
}
一些常见的陷阱:
确保您已正确设置上传目录。
确保您已正确设置上传目录的权限。