Skip to content

Instantly share code, notes, and snippets.

@kylejson
Created March 23, 2014 01:06
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kylejson/9716881 to your computer and use it in GitHub Desktop.
Save kylejson/9716881 to your computer and use it in GitHub Desktop.
Send canvas as image to server/save form input in localStorage
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<form id="form">
<input id="pass" type="password" placeholder="password">
<input type="submit" value="Submit">
</form>
<canvas id="myCanvas" width="578" height="200" style="display:none;"></canvas>
<img id="canvasImg" alt="Right click to save me!">
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// draw cloud
context.beginPath();
context.moveTo(170, 80);
context.bezierCurveTo(130, 100, 130, 150, 230, 150);
context.bezierCurveTo(250, 180, 320, 180, 340, 150);
context.bezierCurveTo(420, 150, 420, 120, 390, 100);
context.bezierCurveTo(430, 40, 370, 30, 340, 50);
context.bezierCurveTo(320, 5, 250, 20, 250, 50);
context.bezierCurveTo(200, 5, 150, 20, 170, 80);
context.closePath();
context.lineWidth = 5;
context.fillStyle = '#8ED6FF';
context.fill();
context.strokeStyle = '#0000ff';
context.stroke();
$('#form').bind('submit', function(e){
e.preventDefault();
var password = $('#pass').val();
localStorage.setItem('form-password', JSON.stringify(password));
});
// save canvas image as data url (png format by default)
var dataURL = canvas.toDataURL();
// set canvasImg image src to dataURL
// so it can be saved as an image
document.getElementById('canvasImg').src = dataURL;
$.ajax({
type: "POST",
url: "http://localhost/test.php",
data: {
imgBase64: dataURL
}
}).done(function(response) {
console.log('saved: ' + response);
});
</script>
</body>
</html>
<?php
define('UPLOAD_DIR', 'images/');
$img = $_POST['imgBase64'];
$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);
//send request to ocr
print $success ? $file : 'Unable to save the file.';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment