我有这个画布。我写了一些JavaScript,允许用户以不同的颜色和笔大小在画布上绘制。
<style>
#myCanvas{
position:absolute;
top:0px;
left:0px;
border:1px solid black;
z-index:0;
}
</style>
<canvas id="myCanvas" width="900" height="600"></canvas>
我将如何让用户单击按钮或输入带有type =“ button”的输入并将图像保存到服务器?
您可以使用以下方式将画布图稿另存为编码图像: canvas.toDataURL
然后,您可以使用AJAX将已编码的图像数据提交到服务器。
这是一些使用jQuery + AJAX将图像数据发布到服务器上文件的代码。
客户端在您的按钮单击事件中:
// 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.';
}
一些常见的陷阱:
确保您已正确设置上传目录。
确保您在上传目录上设置了正确的权限。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句