【问题标题】:Onclick save canvas as image on serverOnclick 将画布保存为服务器上的图像
【发布时间】:2014-06-17 04:24:31
【问题描述】:

我有这个画布。我编写了一些 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" 的输入并将图像保存到服务器?

【问题讨论】:

    标签: html image canvas onclick save


    【解决方案1】:

    您可以使用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.';
    
    }
    

    一些常见的陷阱:

    • 确保您已正确设置上传目录。

    • 确保您已正确设置上传目录的权限。

    【讨论】:

      猜你喜欢
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多