Skip to content

Instantly share code, notes, and snippets.

@mmuoDev
Created February 22, 2018 14:04
Show Gist options
  • Save mmuoDev/e67399c3cf76fd4c060b56dbb5003c1e to your computer and use it in GitHub Desktop.
Save mmuoDev/e67399c3cf76fd4c060b56dbb5003c1e to your computer and use it in GitHub Desktop.
Adding signature to Laravel form.
For this to work, you have to include CDNs for JQuery and FabricJS.
***The View****
===The blade file===
The CSS
<style>
#sheet-container {
width: 250px;
height: 100px;
border: 1px solid black;
}
</style>
<form action="" method="post">
{{csrf_field()}}
<div id="sheet-container">
<canvas id="sheet" width="250" height="100"></canvas>
</div>
<input type="button" class="btn btn-default btn-sm" id="saveSign" value="Add Signature">
<button class="btn btn-danger btn-sm" id="clearSignature">Clear Signature</button>
<!--Add signature here -->
<div id="signature">
</div>
<!--->
<input type="submit" class="btn btn-primary" name="Save" value="Save">
</form>
The JS Script
<script>
var canvas = new fabric.Canvas('sheet');
canvas.isDrawingMode = true;
canvas.freeDrawingBrush.width = 1;
canvas.freeDrawingBrush.color = "#ff0000";
$( '#saveSign' ).click( function( e ) {
e.preventDefault();
var canvas = document.getElementById("sheet");
var dataUrl = canvas.toDataURL("image/png"); //
var saveButton = $(this).val();
if(saveButton == "Add Signature"){
//alert(dataUrl); check if canvas is empty
var blank = isCanvasBlank(canvas);
if(blank){
alert('Signature can\'t be empty');
return false;
}
//Pass signature to the form.
var signature = document.getElementById('signature');
signature.innerHTML = '<input type="hidden" name="signature" value="'+dataUrl+'">';
$(this).val('Remove Signature'); //Update button text
}else if(saveButton == "Remove Signature"){
var signature = document.getElementById('signature');
signature.innerHTML = '';
$(this).val("Add Signature");
}
});
//Clear signature
$('#clearSignature').click(function (e) {
e.preventDefault();
canvas.clear();
});
//Check if canvass is empty
function isCanvasBlank(canvas) {
var blank = document.createElement('canvas');
blank.width = canvas.width;
blank.height = canvas.height;
return canvas.toDataURL() == blank.toDataURL();
}
</script>
***The Controller***
public function index(Request $request){
$method = $request->isMethod('post');
if($method){
dd($request->all());
//Save to database. Recommended data type for the image is blob.
}else{
//Return the view
}
}
***The route***
Route::match(['post', 'get'], '/test', 'SignatureController@index');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment