javascript 将画布图像保存到服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27213366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:09:21  来源:igfitidea点击:

save canvas image to server

javascriptphphtmlcanvas

提问by user3080392

I'm trying to save the canvas image to the server. I can save the file, but it's always 0 bytes. What's wrong with my code?

我正在尝试将画布图像保存到服务器。我可以保存文件,但它总是 0 字节。我的代码有什么问题?

<script>
function test(){
var canvas  = document.getElementById("cvs");
var dataURL = canvas.toDataURL();

$.ajax({
  type: "POST",
  url: "upload.php",
  data: { 
     imgBase64: dataURL
  }
}).done(function(o) {
  console.log('saved'); 

});

}
</script>

php:

php:

<?php    
define('UPLOAD_DIR', 'uploads/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?> 

采纳答案by NatureShade

First you have to be sure that you have painted to the canvas afteryou defined the canvasvariable and beforeyou created the dataURL

首先,您必须确保定义canvas变量之后和创建变量之前已经绘制到画布上dataURL

Second, it seems like you are looking for imgin this php line:

其次,您似乎正在img此 php 行中查找:

$img = $_POST['img'];

but in your javascript you are defining it as imgBase64in:

但是在您的 javascript 中,您将其定义为imgBase64

data: { 
   imgBase64: dataURL
}

lastly you should be adding console.log(dataURL)after the dataURLhas been created to be sure that there is anything in it.

最后,您应该在创建console.log(dataURL)之后添加dataURL,以确保其中有任何内容。