2

画像と画像の上にいくつかの形状を持つキャンバスを作成しました。保存ボタンをクリックしたときに、キャンバス全体を画像として保存する必要があります。どうすればいいですか。誰でも私を助けることができます。

私はあなたが言ったようにしましたが、ここで機能しないのは私のコードです。すべてが含まれているか確認できますか。

<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>
4

1 に答える 1

3

キャンバスを画像 URL に保存し、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 が空でないことを確認してください (このクライアント側を確認することもできます -- 表示されていません)。
  • サーバーでファイルのアップロードが有効になっていることを確認してください。
  • サーバーで適切なファイル アップロード サイズ制限を定義していることを確認してください。
  • アップロード ディレクトリが正しく定義されていることを確認してください。
  • アップロード ディレクトリに適切な権限が設定されていることを確認してください。

...そして、我慢してください。実行するには、サーバーをいじる必要がある場合があります。

于 2013-06-06T23:13:25.337 に答える