Byte image is not being saved in the database from client browser - javascript

I'm really stuck in a problem of saving image. I'm developing a website (asp.net, VB) that will enable users to save signature image in the database. My code works(saves image in the database) when I run in localhost, but published website doesn't save. Please help me to resolve this.
canvas class="roundCorners" id="txtSignature" style="position: relative; margin-left: auto; margin-right: auto; padding-left: 0; padding-right: 0; display: block; border: 1px solid #c4caac; background-color:#fff" >
<script type="text/javascript" >
signatureCapture();
</script>
JavaScript for canvas is:
function signatureCapture() {
var canvas = document.getElementById("txtSignature");
var context = canvas.getContext("2d");
canvas.width = 600;
canvas.height = 200;
context.fillStyle = "#fff";
context.strokeStyle = "#444";
context.lineWidth = 1.5;
context.lineCap = "round";
context.fillRect(0, 0, canvas.width, canvas.height);
var disableSave = true;
var pixels = [];
var cpixels = [];
var xyLast = {};
var xyAddLast = {};
var calculate = false;
{ //functions
function remove_event_listeners() {
canvas.removeEventListener('mousemove', on_mousemove, false);
canvas.removeEventListener('mouseup', on_mouseup, false);
canvas.removeEventListener('touchmove', on_mousemove, false);
canvas.removeEventListener('touchend', on_mouseup, false);
document.body.removeEventListener('mouseup', on_mouseup, false);
document.body.removeEventListener('touchend', on_mouseup, false);
}
function get_coords(e) {
var x, y;
if (e.changedTouches && e.changedTouches[0]) {
var offsety = canvas.offsetTop || 0;
var offsetx = canvas.offsetLeft || 0;
x = e.changedTouches[0].pageX - (offsetx);
y = e.changedTouches[0].pageY - (offsety);
} else if (e.layerX || 0 == e.layerX) {
x = e.layerX;
y = e.layerY;
} else if (e.offsetX || 0 == e.offsetX) {
x = e.offsetX;
y = e.offsetY;
}
return {
x : x,
y : y
};
};
function on_mousedown(e) {
e.preventDefault();
e.stopPropagation();
canvas.addEventListener('mouseup', on_mouseup, false);
canvas.addEventListener('mousemove', on_mousemove, false);
canvas.addEventListener('touchend', on_mouseup, false);
canvas.addEventListener('touchmove', on_mousemove, false);
document.body.addEventListener('mouseup', on_mouseup, false);
document.body.addEventListener('touchend', on_mouseup, false);
empty = false;
var xy = get_coords(e);
context.beginPath();
pixels.push('moveStart');
context.moveTo(xy.x, xy.y);
pixels.push(xy.x, xy.y);
xyLast = xy;
};
function on_mousemove(e, finish) {
e.preventDefault();
e.stopPropagation();
var xy = get_coords(e);
var xyAdd = {
x : (xyLast.x + xy.x) / 2,
y : (xyLast.y + xy.y) / 2
};
if (calculate) {
var xLast = (xyAddLast.x + xyLast.x + xyAdd.x) / 3;
var yLast = (xyAddLast.y + xyLast.y + xyAdd.y) / 3;
pixels.push(xLast, yLast);
} else {
calculate = true;
}
context.quadraticCurveTo(xyLast.x, xyLast.y, xyAdd.x, xyAdd.y);
pixels.push(xyAdd.x, xyAdd.y);
context.stroke();
context.beginPath();
context.moveTo(xyAdd.x, xyAdd.y);
xyAddLast = xyAdd;
xyLast = xy;
};
function on_mouseup(e) {
remove_event_listeners();
disableSave = false;
context.stroke();
pixels.push('e');
calculate = false;
};
}
canvas.addEventListener('touchstart', on_mousedown, false);
canvas.addEventListener('mousedown', on_mousedown, false);
}
function signatureSave() {
var canvas = document.getElementById("txtSignature"); // save canvas image as data url (png format by default)
var dataURL = canvas.toDataURL("image/png");
document.getElementById("saveSignature").src = dataURL;
dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, "")
//alert(dataURL);
// Sending the image data to Server
$.ajax({
type: 'POST',
url: 'Save_Picture.aspx/UploadPic',
data: '{ "imageData" : "' + dataURL + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert("Done, Picture Uploaded.");
}
});
location.href = "Main.aspx";
};

Are you sure you want to do this:
$.ajax({
//... removed to make this answer shorter
success: function (msg) {
alert("Done, Picture Uploaded.");
}
});
//will be executed even before ajax request is done
location.href = "Main.aspx";
Maybe try the following:
$.ajax({
//... removed to make this answer shorter
success: function (msg) {
alert("Done, Picture Uploaded.");
location.href = "Main.aspx";
}
});

Related

how to handle touch on smartphone's browsers - javascript

I want to handle touch listener on smartphones.
my codes works fine with mousedown,mousemove,mouseup,mouseout on web browsers.
canvas.addEventListener("mousedown", function(event) {
event.preventDefault();
var p = get_mouse_position(event);
for( var i=0; i<4; i++ ) {
var x = points[i][0];
var y = points[i][1];
if( p.x < x + 10 && p.x > x - 10 && p.y < y + 10 && p.y > y - 10 ) {
drag = i;
break;
}
}
}, false);
canvas.addEventListener("mousemove", function(event) {
event.preventDefault();
if(drag == null) { return; }
var p = get_mouse_position(event);
points[drag][0] = p.x;
points[drag][1] = p.y;
prepare_lines(ctx2, points, true);
draw_canvas(ctx, ctx1, ctx2);
}, false);
canvas.addEventListener("mouseup", function(event) {
event.preventDefault();
if(drag == null) { return; }
var p = get_mouse_position(event);
points[drag][0] = p.x;
points[drag][1] = p.y;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx1.clearRect(0, 0, canvas.width, canvas.height);
var s = (new Date()).getTime();
op.draw(points);
document.getElementById("ms").innerHTML = ( (new Date()).getTime() - s );
prepare_lines(ctx2, points);
draw_canvas(ctx, ctx1, ctx2);
drag = null;
}, false);
canvas.addEventListener("mouseout", function(event) {
event.preventDefault();
drag = null;
}, false);
canvas.addEventListener("mouseenter", function(event) {
event.preventDefault();
drag = null;
}, false);
like this demo:
http://www.html5.jp/test/perspective_canvas/demo1_en.html
https://github.com/wanadev/perspective.js/
but my codes doesn't work on smartphone's browsers.
I added touchstart,touchmove,touchend listener like same codes on click listeners. but on smartphone's browsers my edges dosn't move at all.
touch listerns:
canvas.addEventListener('touchstart', function(event){
event.preventDefault();
var p = get_mouse_position(event);
for( var i=0; i<4; i++ ) {
var x = points[i][0];
var y = points[i][1];
if( p.x < x + 10 && p.x > x - 10 && p.y < y + 10 && p.y > y - 10 ) {
drag = i;
break;
}
}
}, false);
canvas.addEventListener('touchmove', function(event){
event.preventDefault();
if(drag == null) { return; }
var p = get_mouse_position(event);
points[drag][0] = p.x;
points[drag][1] = p.y;
prepare_lines(ctx2, points, true);
draw_canvas(ctx, ctx1, ctx2);
}, false);
canvas.addEventListener('touchend', function(event){
event.preventDefault();
if(drag == null) { return; }
var p = get_mouse_position(event);
points[drag][0] = p.x;
points[drag][1] = p.y;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx1.clearRect(0, 0, canvas.width, canvas.height);
var s = (new Date()).getTime();
op.draw(points);
document.getElementById("ms").innerHTML = ( (new Date()).getTime() - s );
prepare_lines(ctx2, points);
draw_canvas(ctx, ctx1, ctx2);
drag = null;
}, false);
I want to handle 4-edges on smartphone's browsers like web browsers. but I can't move 4-edges on smartphone's browsers.
A TouchEvent might be composed of multiple Touch objects (a.k.a multitouch).
These different Touch objects are available through the .touches TouchList property of the Event.
Only these objects will hold the coordinates you are interested in, and thus, in your handler, you need to pick one of these Touch object, this is generally the first one (single-touch application).
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
// attach all our handlers
canvas.addEventListener('mousedown', handleDown);
canvas.addEventListener('touchstart', handleDown);
document.addEventListener('mouseup', handleUp);
document.addEventListener('touchend', handleUp);
document.addEventListener('mousemove', handleMove);
document.addEventListener('touchmove', handleMove);
var mouse = {
lastX: null,
lastY: null,
x: null,
y: null,
down: false
};
// Here we want to check whether it is a touch event or a mouse event
function update_coords(evt) {
evt.preventDefault();
var ev;
// touch event?
if (evt.touches && evt.touches.length) {
ev = evt.touches[0];
} else ev = evt; // mouse
var rect = canvas.getBoundingClientRect();
// update our mouse object
mouse.lastX = mouse.x;
mouse.lastY = mouse.y;
mouse.x = ev.clientX - rect.left;
mouse.y = ev.clientY - rect.top;
}
function handleDown(evt) {
mouse.down = true;
update_coords(evt);
draw();
}
function handleUp(evt) {
mouse.down = false;
mouse.lastX = mouse.lastY = mouse.x = mouse.y = null;
}
function handleMove(evt) {
if (mouse.down) {
update_coords(evt);
draw();
}
}
function draw() {
if(mouse.lastX === null) return;
ctx.beginPath();
ctx.moveTo(mouse.lastX, mouse.lastY);
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
}
canvas{
border: 1px solid;
}
<canvas id="canvas" width="500" height="300"></canvas>
To test on a mobile device, please switch to the full site version of Stackoverflow (at the bottom of the page) or try this fiddle.

Extending existing canvas signing script

I lack javascript / Jquery skills to extend the script like I want. I wanted to use this script to have 3 signfields on a page. All 3 will be signed separately and should be saved later as 3 images to create a PDF via FPDF with. My problem is that 3x "" doesnt provide the hoped for result. Thats why I wanted to ask If some1 could explain to me how to do that.
Greetings.
var isSign = false;
var leftMButtonDown = false;
jQuery(function() {
//Initialize sign pad
init_Sign_Canvas();
});
function fun_submit() {
if (isSign) {
var canvas = $("#canvas").get(0);
var imgData = canvas.toDataURL();
jQuery('#page').find('p').remove();
jQuery('#page').find('img').remove();
jQuery('#page').append(jQuery('<p>Your Sign:</p>'));
jQuery('#page').append($('<img/>').attr('src', imgData));
closePopUp();
} else {
alert('Please sign');
}
}
function closePopUp() {
jQuery('#divPopUpSignContract').popup('close');
jQuery('#divPopUpSignContract').popup('close');
}
function init_Sign_Canvas() {
isSign = false;
leftMButtonDown = false;
//Set Canvas width
var sizedWindowWidth = $(window).width();
if (sizedWindowWidth > 700)
sizedWindowWidth = $(window).width() / 2;
else if (sizedWindowWidth > 350)
sizedWindowWidth = sizedWindowWidth - 100;
else
sizedWindowWidth = sizedWindowWidth - 50;
$("#canvas").width(350);
$("#canvas").height(100);
$("#canvas").css("border", "1px solid #000");
var canvas = $("#canvas").get(0);
canvasContext = canvas.getContext('2d');
if (canvasContext) {
canvasContext.canvas.width = 350;
canvasContext.canvas.height = 100;
canvasContext.fillStyle = "#fff";
canvasContext.fillRect(0, 0, sizedWindowWidth, 350);
canvasContext.moveTo(100, 150);
canvasContext.lineTo(sizedWindowWidth - 50, 150);
canvasContext.stroke();
canvasContext.fillStyle = "#000";
canvasContext.font = "20px Arial";
canvasContext.fillText("x", 40, 155);
}
// Bind Mouse events
$(canvas).on('mousedown', function(e) {
if (e.which === 1) {
leftMButtonDown = true;
canvasContext.fillStyle = "#000";
var x = e.pageX - $(e.target).offset().left;
var y = e.pageY - $(e.target).offset().top;
canvasContext.moveTo(x, y);
}
e.preventDefault();
return false;
});
$(canvas).on('mouseup', function(e) {
if (leftMButtonDown && e.which === 1) {
leftMButtonDown = false;
isSign = true;
}
e.preventDefault();
return false;
});
// draw a line from the last point to this one
$(canvas).on('mousemove', function(e) {
if (leftMButtonDown == true) {
canvasContext.fillStyle = "#000";
var x = e.pageX - $(e.target).offset().left;
var y = e.pageY - $(e.target).offset().top;
canvasContext.lineTo(x, y);
canvasContext.stroke();
}
e.preventDefault();
return false;
});
//bind touch events
$(canvas).on('touchstart', function(e) {
leftMButtonDown = true;
canvasContext.fillStyle = "#000";
var t = e.originalEvent.touches[0];
var x = t.pageX - $(e.target).offset().left;
var y = t.pageY - $(e.target).offset().top;
canvasContext.moveTo(x, y);
e.preventDefault();
return false;
});
$(canvas).on('touchmove', function(e) {
canvasContext.fillStyle = "#000";
var t = e.originalEvent.touches[0];
var x = t.pageX - $(e.target).offset().left;
var y = t.pageY - $(e.target).offset().top;
canvasContext.lineTo(x, y);
canvasContext.stroke();
e.preventDefault();
return false;
});
$(canvas).on('touchend', function(e) {
if (leftMButtonDown) {
leftMButtonDown = false;
isSign = true;
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="canvas">Canvas is not supported</canvas>
<canvas id="canvas">Canvas is not supported</canvas>
<canvas id="canvas">Canvas is not supported</canvas>

JavaScript Canvas create square [duplicate]

This question already has an answer here:
Drawing a rectangle on Canvas
(1 answer)
Closed 5 years ago.
I want to draw a square with a function like following.
How can I modify following function to create a square.
function square() {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
context.beginPath();
context.moveTo(ev._x, ev._y);
tool.started = true;
};
this.mousemove = function (ev) {
if (tool.started && checkboxSquare.checked) {
context.lineTo(ev._x, ev._y);
context.stroke();
}
};
this.mouseup = function (ev) {
if (tool.started && checkboxSquare.checked) {
tool.mousemove(ev);
tool.started = false;
}
};
}
Here is a rework:
var Square;
(function(Square) {
var canvas = document.body.appendChild(document.createElement("canvas"));
canvas.style.border = "1px solid";
canvas.width = 800;
canvas.height = 800;
var context = canvas.getContext("2d");
var drawing = false;
var square = {
x: 0,
y: 0,
w: 0,
h: 0,
color: getColor()
};
var persistentSquares = [];
function getColor() {
return "rgb(" +
Math.round(Math.random() * 255) + ", " +
Math.round(Math.random() * 255) + ", " +
Math.round(Math.random() * 255) + ")";
}
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
for (var pSquareIndex = 0; pSquareIndex < persistentSquares.length; pSquareIndex++) {
var pSquare = persistentSquares[pSquareIndex];
context.fillStyle = pSquare.color;
context.fillRect(pSquare.x, pSquare.y, pSquare.w - pSquare.x, pSquare.h - pSquare.y);
context.strokeRect(pSquare.x, pSquare.y, pSquare.w - pSquare.x, pSquare.h - pSquare.y);
}
context.strokeRect(square.x, square.y, square.w - square.x, square.h - square.y);
}
canvas.onmousedown = function(evt) {
square.x = evt.offsetX;
square.y = evt.offsetY;
square.w = evt.offsetX;
square.h = evt.offsetY;
drawing = true;
requestAnimationFrame(draw);
};
canvas.onmousemove = function(evt) {
if (drawing) {
square.w = evt.offsetX;
square.h = evt.offsetY;
requestAnimationFrame(draw);
}
};
function leave(evt) {
if (!drawing) {
return;
}
square.w = evt.offsetX;
square.h = evt.offsetY;
drawing = false;
persistentSquares.push(square);
square = {
x: 0,
y: 0,
w: 0,
h: 0,
color: getColor()
};
requestAnimationFrame(draw);
};
canvas.onmouseup = leave;
canvas.onmouseleave = leave;
})(Square || (Square = {}));
It's your lucky day! I was just working on something like this. If you use it for anything, be sure to credit me! ;)
Note that circle and oval are still a Work in Progress.
Link to JSFiddle that will be updated when I update the program: JSFiddle
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var mx=300;
var my=300;
var currentObject = {};
document.onmousemove = function(e){
mx=e.pageX-8;
my=e.pageY-8;
}
document.onmousedown = function(e){
var obj = document.getElementById("objSel").value;
currentObject.type=obj;
if(obj=="Rectangle"||currentObject.type=="Square"){
currentObject.x=e.pageX-8;
currentObject.y=e.pageY-8;
}
}
document.onmouseup = function(e){
mx=e.pageX-8;
my=e.pageY-8;
objects.push(complete(currentObject));
currentObject={};
}
var objects = [];
function render(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.moveTo(mx-5,my);
ctx.lineTo(mx+5,my);
ctx.moveTo(mx,my-5);
ctx.lineTo(mx,my+5);
ctx.strokeStyle="black";
ctx.lineWidth=2;
ctx.stroke();
ctx.closePath();
if(currentObject.type=="Rectangle"){
ctx.beginPath();
ctx.rect(currentObject.x,currentObject.y,mx-currentObject.x,my-currentObject.y);
ctx.stroke();
}
draw(complete(currentObject));
for(var i=0;i<objects.length;i++){
draw(objects[i]);
}
}
setInterval(render,5);
render();
function complete(o){
if(o.type=="Square"){
var sidelength = Math.max(Math.abs(mx-o.x),Math.abs(my-o.y));
var fix = function(input){
if(input==0){
return 1;
} else {
return input;
}
};
o.length=fix(Math.sign(mx-o.x))*sidelength;
o.height=fix(Math.sign(my-o.y))*sidelength;
} else if(o.type=="Rectangle"){
o.length=mx-o.x;
o.height=my-o.y;
}
return o;
}
function draw(o){
if(o.type=="Square"||o.type=="Rectangle"){
ctx.beginPath();
ctx.rect(o.x,o.y,o.length,o.height);
ctx.stroke();
}
}
<canvas id="canvas" style="border:1px solid black;" width="500" height="500">Please use a browser that supports the canvas element and make sure your Javascript is working properly.</canvas>
<br>
<span id="testing"></span>
<select id="objSel">
<option>Square</option>
<option>Rectangle</option>
<option>Circle</option>
<option>Oval</option>
</select>

Custom sizing tool is not working in Canvas Drawing

Here is my fiddle
HTML for Canvas:
<div id="canvasDiv"><canvas id="myNewCanvasColumn" width="490" height="220"></canvas></div>
I am working on a canvas drawing tool. Problem is that, i am unable to select the appropriate sizes for drawing. I have defined sizes like "small, normal, large and huge". Default selection is normal. I have wrote some function to determine the radius, but it is not working. Can some one help me?
Thanks a ton..!
You can set different context.lineWidth to set the cursor size. I've updated the code with that.
function redraw() {
clickSize.length = 0;
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
//context.strokeStyle = "#df4b26";
context.lineJoin = "round";
//context.lineWidth = 5;
for (var i = 0; i < clickX.length; i++) {
context.beginPath();
if (clickDrag[i] && i) {
context.moveTo(clickX[i - 1], clickY[i - 1]);
} else {
context.moveTo(clickX[i] - 1, clickY[i]);
}
context.lineTo(clickX[i], clickY[i]);
context.closePath();
context.strokeStyle = clickColor[i];
context.lineWidth = cursorSize;
//alert('radius is'+context.lineWidth)
context.stroke();
}
}
$('#choosesmall').click(function () {
curSize = "small";
cursorSize = 1;
});
$('#choosenormal').click(function () {
curSize = "normal";
cursorSize = 3;
});
$('#chooselarge').click(function () {
curSize = "large";
cursorSize = 5;
});
$('#choosehuge').click(function () {
curSize = "huge";
cursorSize = 7;
});
See the Fiddle
Edit
$(document).ready(function () {
/* Declaration global Variables */
var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;
var context;
var canvas;
var colorPurple = "#cb3594";
var colorGreen = "#659b41";
var colorYellow = "#ffcf33";
var colorBrown = "#986928";
var colorRed = "#ff0000";
var curColor = colorPurple;
var clickColor = new Array();
var clickSize = new Array();
var curSize = 1;
/* End of Declaring Global Variables */
context = document.getElementById('myNewCanvasColumn').getContext("2d");
var canvasDiv = document.getElementById('canvasDiv');
canvas = document.createElement('canvas');
canvas.setAttribute('width', 700);
canvas.setAttribute('height', 300);
canvas.setAttribute('id', 'canvas');
canvasDiv.appendChild(canvas);
if (typeof G_vmlCanvasManager != 'undefined') {
canvas = G_vmlCanvasManager.initElement(canvas);
}
var radius;
var i = 0;
context = canvas.getContext("2d");
/* Event Handlers for drawing */
$('#canvas').mousedown(function (e) {
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
paint = true;
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
redraw();
});
$('#canvas').mousemove(function (e) {
if (paint) {
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
redraw();
}
});
$('#canvas').mouseup(function (e) {
paint = false;
});
$('#canvas').mouseleave(function (e) {
paint = false;
});
$("#clear").click(function () {
clearDrawing();
});
/* End of Event Handlers */
/* Custom Color Pickers */
$('#choosegreen').click(function () {
curColor = "#659b41";
});
$('#choosepurple').click(function () {
curColor = "#cb3594";
});
$('#chooseyellow').click(function () {
curColor = "#ffcf33";
});
$('#choosebrown').click(function () {
curColor = "#986928";
});
$('#choosered').click(function () {
curColor = "#ff0000";
});
/* End of Custom Color Pickers */
/* Custom Size Picker */
$('#choosesmall').click(function () {
curSize = 1;
});
$('#choosenormal').click(function () {
curSize = 3;
});
$('#chooselarge').click(function () {
curSize = 5;
});
$('#choosehuge').click(function () {
curSize = 7;
});
/* End of Custom Size Picker */
function addClick(x, y, dragging) {
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
clickColor.push(curColor);
clickSize.push(curSize);
// alert(clickSize);
}
function clearDrawing() {
clickX.length = 0;
clickY.length = 0;
clickDrag.length = 0;
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
}
function redraw() {
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
//context.strokeStyle = "#df4b26";
context.lineJoin = "round";
//context.lineWidth = 5;
for (var i = 0; i < clickX.length; i++) {
context.beginPath();
if (clickDrag[i] && i) {
context.moveTo(clickX[i - 1], clickY[i - 1]);
} else {
context.moveTo(clickX[i] - 1, clickY[i]);
}
context.lineTo(clickX[i], clickY[i]);
context.closePath();
context.strokeStyle = clickColor[i];
context.lineWidth = clickSize[i];
// alert(clickColor[i]);
//alert('radius is'+context.lineWidth)
context.stroke();
}
}
});
Updated Fiddle

How do I save the captured image of a signature to MySQL

I have a script that captures a signature on a touch screen and saves it as an image, I can't figure out how to then submit that image to MySQL. Do I need to add the name tag to the image and use that as the variable or can I use the id tag as the variable? I know how to upload an image to a folder on the server and save the path to the image in MySQL, I'm just not sure how to save this image!
Here is my
jsFiddle
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="signature/todataurl.js"></script>
<script src="signature/signature.js"></script>
</head>
<body>
<center>
<div id="canvas">
<canvas class="roundCorners" id="newSignature"
style="position: relative; margin: 0; padding: 0; border: 1px solid #c4caac; left: 0px; top: 0px;" height="124" width="524"></canvas>
</div>
<script>
signatureCapture();
</script>
<br/><br/>
<button type="button" onclick="signatureSave()">
Save signature
</button>
<button type="button" onclick="signatureClear()">
Clear signature
</button>
<br/>
Saved Image
<br/>
<img id="saveSignature" alt="Saved image png"/>
</center>
</body>
</html>
And the JavaScript:
function signatureCapture() {
var canvas = document.getElementById("newSignature");
var context = canvas.getContext("2d");
canvas.width = 276;
canvas.height = 180;
context.fillStyle = "#fff";
context.strokeStyle = "#444";
context.lineWidth = 1.5;
context.lineCap = "round";
context.fillRect(0, 0, canvas.width, canvas.height);
var disableSave = true;
var pixels = [];
var cpixels = [];
var xyLast = {};
var xyAddLast = {};
var calculate = false;
{ //functions
function remove_event_listeners() {
canvas.removeEventListener('mousemove', on_mousemove, false);
canvas.removeEventListener('mouseup', on_mouseup, false);
canvas.removeEventListener('touchmove', on_mousemove, false);
canvas.removeEventListener('touchend', on_mouseup, false);
document.body.removeEventListener('mouseup', on_mouseup, false);
document.body.removeEventListener('touchend', on_mouseup, false);
}
function get_coords(e) {
var x, y;
if (e.changedTouches && e.changedTouches[0]) {
var offsety = canvas.offsetTop || 0;
var offsetx = canvas.offsetLeft || 0;
x = e.changedTouches[0].pageX - offsetx;
y = e.changedTouches[0].pageY - offsety;
} else if (e.layerX || 0 == e.layerX) {
x = e.layerX;
y = e.layerY;
} else if (e.offsetX || 0 == e.offsetX) {
x = e.offsetX;
y = e.offsetY;
}
return {
x : x,
y : y
};
};
function on_mousedown(e) {
e.preventDefault();
e.stopPropagation();
canvas.addEventListener('mouseup', on_mouseup, false);
canvas.addEventListener('mousemove', on_mousemove, false);
canvas.addEventListener('touchend', on_mouseup, false);
canvas.addEventListener('touchmove', on_mousemove, false);
document.body.addEventListener('mouseup', on_mouseup, false);
document.body.addEventListener('touchend', on_mouseup, false);
empty = false;
var xy = get_coords(e);
context.beginPath();
pixels.push('moveStart');
context.moveTo(xy.x, xy.y);
pixels.push(xy.x, xy.y);
xyLast = xy;
};
function on_mousemove(e, finish) {
e.preventDefault();
e.stopPropagation();
var xy = get_coords(e);
var xyAdd = {
x : (xyLast.x + xy.x) / 2,
y : (xyLast.y + xy.y) / 2
};
if (calculate) {
var xLast = (xyAddLast.x + xyLast.x + xyAdd.x) / 3;
var yLast = (xyAddLast.y + xyLast.y + xyAdd.y) / 3;
pixels.push(xLast, yLast);
} else {
calculate = true;
}
context.quadraticCurveTo(xyLast.x, xyLast.y, xyAdd.x, xyAdd.y);
pixels.push(xyAdd.x, xyAdd.y);
context.stroke();
context.beginPath();
context.moveTo(xyAdd.x, xyAdd.y);
xyAddLast = xyAdd;
xyLast = xy;
};
function on_mouseup(e) {
remove_event_listeners();
disableSave = false;
context.stroke();
pixels.push('e');
calculate = false;
};
}
canvas.addEventListener('touchstart', on_mousedown, false);
canvas.addEventListener('mousedown', on_mousedown, false);
}
function signatureSave() {
var canvas = document.getElementById("newSignature");// save canvas image as data url (png format by default)
var dataURL = canvas.toDataURL("image/png");
document.getElementById("saveSignature").src = dataURL;
};
function signatureClear() {
var canvas = document.getElementById("newSignature");
var context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
}
and here is the todataurl.js code:
Number.prototype.toUInt=function(){ return this<0?this+4294967296:this; };
Number.prototype.bytes32=function(){ return [(this>>>24)&0xff,(this>>>16)&0xff,(this>>>8)&0xff,this&0xff]; };
Number.prototype.bytes32sw=function(){ return [this&0xff,(this>>>8)&0xff,(this>>>16)&0xff,(this>>>24)&0xff]; };
Number.prototype.bytes16=function(){ return [(this>>>8)&0xff,this&0xff]; };
Number.prototype.bytes16sw=function(){ return [this&0xff,(this>>>8)&0xff]; };
Array.prototype.adler32=function(start,len){
switch(arguments.length){ case 0:start=0; case 1:len=this.length-start; }
var a=1,b=0;
for(var i=0;i<len;i++){
a = (a+this[start+i])%65521; b = (b+a)%65521;
}
return ((b << 16) | a).toUInt();
};
Array.prototype.crc32=function(start,len){
switch(arguments.length){ case 0:start=0; case 1:len=this.length-start; }
var table=arguments.callee.crctable;
if(!table){
table=[];
var c;
for (var n = 0; n < 256; n++) {
c = n;
for (var k = 0; k < 8; k++)
c = c & 1?0xedb88320 ^ (c >>> 1):c >>> 1;
table[n] = c.toUInt();
}
arguments.callee.crctable=table;
}
var c = 0xffffffff;
for (var i = 0; i < len; i++)
c = table[(c ^ this[start+i]) & 0xff] ^ (c>>>8);
return (c^0xffffffff).toUInt();
};
(function(){
var toDataURL=function(){
var imageData=Array.prototype.slice.call(this.getContext("2d").getImageData(0,0,this.width,this.height).data);
var w=this.width;
var h=this.height;
var stream=[
0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,
0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52
];
Array.prototype.push.apply(stream, w.bytes32() );
Array.prototype.push.apply(stream, h.bytes32() );
stream.push(0x08,0x06,0x00,0x00,0x00);
Array.prototype.push.apply(stream, stream.crc32(12,17).bytes32() );
var len=h*(w*4+1);
for(var y=0;y<h;y++)
imageData.splice(y*(w*4+1),0,0);
var blocks=Math.ceil(len/32768);
Array.prototype.push.apply(stream, (len+5*blocks+6).bytes32() );
var crcStart=stream.length;
var crcLen=(len+5*blocks+6+4);
stream.push(0x49,0x44,0x41,0x54,0x78,0x01);
for(var i=0;i<blocks;i++){
var blockLen=Math.min(32768,len-(i*32768));
stream.push(i==(blocks-1)?0x01:0x00);
Array.prototype.push.apply(stream, blockLen.bytes16sw() );
Array.prototype.push.apply(stream, (~blockLen).bytes16sw() );
var id=imageData.slice(i*32768,i*32768+blockLen);
Array.prototype.push.apply(stream, id );
}
Array.prototype.push.apply(stream, imageData.adler32().bytes32() );
Array.prototype.push.apply(stream, stream.crc32(crcStart, crcLen).bytes32() );
stream.push(0x00,0x00,0x00,0x00,0x49,0x45,0x4e,0x44);
Array.prototype.push.apply(stream, stream.crc32(stream.length-4, 4).bytes32() );
return "data:image/png;base64,"+btoa(String.fromCharCode.apply(null,stream));
};
var tdu=HTMLCanvasElement.prototype.toDataURL;
HTMLCanvasElement.prototype.toDataURL=function(type){
var res=tdu.apply(this,arguments);
if(res.substr(0,6)=="data:,"){
HTMLCanvasElement.prototype.toDataURL=toDataURL;
return this.toDataURL();
}else{
HTMLCanvasElement.prototype.toDataURL=tdu;
return res;
}
}
})();
submit image data that you get from your canvas using AJAX:
$.ajax(url, {
type: "POST",
data: canvas.toDataURL("image/png"),
success: function (data, status, jqxhr) {...},
error: function (jqxhr, status, error) {...}
});

Categories

Resources