2014-04-30 7 views
1

나는이 캔버스가 있습니다. 사용자가 다른 색상과 펜 크기로 캔버스를 그릴 수있는 자바 스크립트를 작성했습니다.Onclick 서버에 이미지로 캔버스 저장

<style> 
#myCanvas{ 
position:absolute; 
top:0px; 
left:0px; 
border:1px solid black; 
z-index:0; 
} 
</style> 

<canvas id="myCanvas" width="900" height="600"></canvas> 
나는 버튼 또는 = "버튼" 유형의 입력에 사용자가 클릭을 서버에 저장되는 이미지가 얼마나

?

답변

2

그런 다음 서버에 그 인코딩 된 이미지 데이터를 제출 AJAX를 사용할 수 canvas.toDataURL

로 인코딩 된 이미지로 캔버스 작품을 절약 할 수 있습니다.

다음은 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.'; 

} 

일부 보통 개는 :

  • 이 제대로 업로드 디렉토리를 설정했는지 확인하십시오.

  • 업로드 디렉토리에 대한 권한이 올바르게 설정되어 있는지 확인하십시오.

관련 문제