我想将我的div数据转换为图像,并在单击按钮时使用Ajax请求将其存储在目录和数据库中。该代码执行良好,并且将数据存储在目录和db中,但是问题是,当我第一次单击该按钮时,它什么也没做,但是当我第二次单击该按钮时,依此类推,它在两个目录中都正确存储了图像的地方。 我不知道我要去哪里错了,任何建议将不胜感激。 谢谢!
我的查看代码:
<div id='calendar'>-- Data I want to convert to image --</div>
<form method="post" enctype="multipart/form-data" id="myForm">
{{csrf_field()}}
<input type="hidden" name="img_val" id="img_val" value="" />
<input type="submit" id="take_shot" value="Take Screenshot"/>
</form>
我的Jquery代码:
<!-- Canvas Jquery Code for saving screenshot -->
<meta name="csrf-token" content="{{ csrf_token() }}" />
<meta name="screenShot" content="{{url('htmlcanvas')}}">
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
<script type="text/javascript">
$(document).ready(function(){
var dataurl = "";
$('#take_shot').click(function(){
$('#calendar').html2canvas({
onrendered: function (canvas) {
//Set hidden field's value to image data (base-64 string)
dataurl = $('#img_val').val(canvas.toDataURL("image/png"));
}
});
var form_data = new FormData($("#myForm")[0]);
$.ajax({
type:'POST',
url: $('meta[name="screenShot"]').attr('content'),
data : form_data,
cache: false,
processData: false,
contentType: false,
success:function(data){
alert(data);
}
});
return false;
});
});
</script>
我的控制器代码:
public function storeImageHtmlCanvas(Request $request)
{
if($request->ajax()) {
if($request->img_val != null)
{
$dbImage = new Admin_Image;
$data_uri = $request->img_val;
$encoded_image = explode(",", $data_uri)[1];
$decoded_image = base64_decode($encoded_image);
$path = storage_path() . '/screenshots/';
$file_name = time();
file_put_contents($path.$file_name.".png", $decoded_image);
$dbImage->admin_image = $file_name.".png" ;
$dbImage->save();
$output = "success";
}
return response()->json($output);
}
}
答案 0 :(得分:0)
html2canvas
是异步的(〜=它在脚本继续运行时在后台执行),因此当第一个Ajax请求运行时,dataurl
未定义。
您需要在onrendered
函数内部触发AJAX请求,
$('#take_shot').click(function(){
$('#calendar').html2canvas({
onrendered: function (canvas) {
//Set hidden field's value to image data (base-64 string)
dataurl = $('#img_val').val(canvas.toDataURL("image/png"));
// dataurl is defined, you can trigger the ajax request
var form_data = new FormData($("#myForm")[0]);
$.ajax({
type:'POST',
url: $('meta[name="screenShot"]').attr('content'),
data : form_data,
cache: false,
processData: false,
contentType: false,
success:function(data){
alert(data);
}
});
}
});
return false;
});
});