将画布保存为图像PaperJS

时间:2013-06-06 21:43:31

标签: javascript html5-canvas paperjs

我在图像上创建了一个图像和几何形状的画布。现在,当我点击保存按钮时,我需要将整个画布保存为图像。我该怎么做。任何人都可以帮助我。

我按照你的说法做了但不在这里工作的是我的代码。你能检查我是否包含了所有内容。

<canvas id="canvas" resize></canvas>

我包含的Javascript文件是

<script src="lib/jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="lib/paper.js"></script>

以下是代码:

<script>
var canvas = document.getElementById('canvas');
var dataURL = canvas.toDataURL();
    $(document).ready(function(){
        $(".save").click(function(){
            $.ajax({
                type: "POST",
                url: "savepic.php",
                data: {image: dataURL}
            }).done(function(respond){
                console.log(respond);
            });
        });
    });
</script>

1 个答案:

答案 0 :(得分:3)

将画布保存到图像网址并将其上传到PHP服务器

您可以将画布保存为这样的图像URL(默认为.png格式):

canvas.toDataURL();

以下是如何在服务器上发布dataURL。

客户端:

// create a dataUrl from the canvas
var dataURL= canvas.toDataURL();

// use jQuery to POST the dataUrl to you php server
$.ajax({
    type: "POST",
    url: "upload.php",
    data: {image: dataURL}
}).done(function( respond ) {
    // Done...report success or failure
    // You will get back the temp file name
    // or "Unable to save this image."
    console.log(respond);
});

服务器文件: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.';

}

一些常见的问题(注意xampp对这些问题特别敏感):

  • 确保dataURL不为空(您甚至可以检查此客户端 - 未显示)。
  • 确保您已在服务器上启用文件上传。
  • 确保您已在服务器上定义了足够的文件上传大小限制。
  • 确保您已正确定义上传目录。
  • 确保您在上传目录中正确设置了权限。

...而且,请耐心等待。您可能需要修改服务器才能运行。

相关问题