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

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) {...}
});

Related

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>

Is it possible to drag an image within canvas as well as draw on the same canvas?

Here I'm trying to draw on a html5 canvas as well as upload some images and drag them within the canvas. The problem is I can do one or the other but not both.
What I've realised is that the canvas must be Cleared before dragging takes place but by doing that I'm clearing the drawing and if I don't clear the canvas it draws but dragging an image leaves trail behind. Can anyone point me to right direction please.
function init() {
canvas = document.getElementById('can');
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
img = document.getElementById("drag");
canvas.addEventListener("mousemove", function (e) { findxy('move', e) }, false);
canvas.addEventListener("mousedown", function (e) { findxy('down', e) }, false);
canvas.addEventListener("mouseup", function (e) { findxy('up', e) }, false);
canvas.addEventListener("mouseout", function (e) { findxy('out', e) }, false);
imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var contexts = [];
contexts.push(canvas.getContext('2d'));
function clearAll() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
canvas.onclick = function (e) { handleClick(e, 1); };
function handleClick(e, contextIndex) {
e.stopPropagation();
var mouseX = parseInt(e.clientX - e.target.offsetLeft);
var mouseY = parseInt(e.clientY - e.target.offsetTop);
// clearAll();
for (var i = 0; i < states.length; i++) {
var state = states[i];
if (state.dragging) {
state.dragging = false;
state.draw();
continue;
}
if (state.contextIndex === contextIndex
&& mouseX > state.x && mouseX < state.x + state.width
&& mouseY > state.y && mouseY < state.y + state.height)
{
state.dragging = true;
state.offsetX = mouseX - state.x;
state.offsetY = mouseY - state.y;
state.contextIndex = contextIndex;
}
state.draw();
}
}
canvas.onmousemove = function (e) { handleMousemove(e, 1); }
function handleMousemove(e, contextIndex) {
e.stopPropagation();
var mouseX = parseInt(e.clientX - e.target.offsetLeft);
var mouseY = parseInt(e.clientY - e.target.offsetTop);
// clearAll();
for (var i = 0; i < states.length; i++) {
var state = states[i];
if (state.dragging) {
state.x = mouseX - state.offsetX;
state.y = mouseY - state.offsetY;
state.contextIndex = contextIndex;
}
state.draw();
}
}
var states = [];
states.push(addState(0, 0, img));
function addState(x, y, image) {
state = {}
state.dragging = false;
state.contextIndex = 1;
state.image = image;
state.x = x;
state.y = y;
state.width = image.width;
state.height = image.height;
state.offsetX = 0;
state.offsetY = 0;
state.draw = function () {
var context = contexts[this.contextIndex - 1];
if (this.dragging) {
context.strokeStyle = 'red';
context.strokeRect(this.x, this.y, this.width + 5, this.height + 5);
}
context.drawImage(this.image, this.x, this.y);
};
state.draw();
return(state);
}
}//end of init()
var imgArray = [];
function handleImage(e) {
var reader = new FileReader();
reader.onload = function (event) {
imgArray.push(img);
for(i = 0; i < imgArray.length; i++){
img.src = imgArray[i];
img.setAtX = i * 50;
img.setAtY = i * 0;
img.onload = function() {
ctx.drawImage(this, this.setAtX, this.setAtY);
};
img.src = event.target.result;
}
};
reader.readAsDataURL(e.target.files[0]);
}
function findxy(res, e) {
if (res === 'down') {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
flag = true;
dot_flag = true;
if (dot_flag) {
ctx.beginPath();
ctx.fillStyle = x;
ctx.fillRect(currX, currY, 2, 2);
ctx.closePath();
dot_flag = false;
}
}
if (res === 'up' || res === "out") {
flag = false;
}
if (res === 'move') {
if (flag) {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
draw();
}
}
}
//Draw lines or text
function draw() {
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(currX, currY);
ctx.strokeStyle = x;
ctx.lineWidth = y;
ctx.stroke();
ctx.closePath();
ctx.fillStyle = x;
ctx.font = "Italic Bold 14pt Times, serif";
ctx.fillText(message, prevX, prevY);
}
Here is a mashup of the code i linked to and your own.
All parameters related to drawing the image and translating it around the canvas is covered.
var canvas = document.getElementById("canvas");
var ctx;
var x = 75;
var y = 50;
var WIDTH = 400;
var HEIGHT = 300;
var dragok = false;
var img = document.getElementById("img");
var lines = [{
x: x,
y: y
}];
function rect(x, y, w, h) {
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
return setInterval(draw, 1000/24);
}
function draw() {
clear();
ctx.drawImage(img, x - img.width / 2, y - img.height / 2);
ctx.beginPath();
ctx.moveTo(lines[0].x,lines[0].y);
for(var i = 1; i < lines.length; i++) {
var line = lines[i];
ctx.lineTo(lines[i].x,lines[i].y);
}
ctx.stroke();
ctx.closePath();
//rect(x - 15, y - 15, 30, 30);
}
function myMove(e) {
if (dragok) {
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
lines = lines.slice(lines.length - 100)
lines.push({
x: x,
y: y
});
}
}
function myDown(e) {
if (e.pageX < x + img.width / 2 + canvas.offsetLeft && e.pageX > x - img.width / 2 +
canvas.offsetLeft && e.pageY < y + img.height / 2 + canvas.offsetTop &&
e.pageY > y - img.height / 2 + canvas.offsetTop) {
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
dragok = true;
canvas.onmousemove = myMove;
}
}
function myUp() {
dragok = false;
canvas.onmousemove = null;
}
init();
canvas.onmousedown = myDown;
canvas.onmouseup = myUp;
//Change image for the heck of it ^^
setInterval(function() {
img.src = 'https://placeholdit.imgix.net/~text?txtsize=60&txt=' +
Math.floor(Math.random() * 10) +
'&w=100&h=100';
}, 3000)
<canvas id="canvas" width="400" height="300">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
<img id="img" src="https://placeholdit.imgix.net/~text?txtsize=60&txt=1&w=100&h=100">
Updated my answer to draw lines
My final code that's working , I had to add two canvases one for the drawing and one for the dragging images. Fabric frame work helped a lot. https://jsfiddle.net/tn07Bond/982s4bgv/2/
<div id="canvasesdiv">
<canvas id="images" width=600 height=400 style="position: absolute;
left: 0;
top: 0;
border: 1px solid blue;
z-index: 1;">
This text is displayed if your browser does not support HTML5 Canvas</canvas>
<canvas id="drawing" width=600 height=400 style="position: absolute;
left: 0;
top: 0;
border: 1px solid red;
z-index: 2;">
This text is displayed if your browser does not support HTML5 Canvas</canvas>
<input type="file" id="imageLoader" class="imageLoader" name="imageLoader"/>
<input type="image" src="images/PenForCanvas.png" alt="pen" title="Draw on canvas"
id="Drawing" style="cursor: pointer; margin: 5px 0 0 200px;">
<input type="image" src="images/drag.png" alt="drag" title="Drag this image" id="Images" style="cursor: pointer;">
</div>
<script>
var drawing, drawingCtx,images,imagesCtx, message = "", img, imageLoader, prevX = 10, currX = 10, prevY = 10, currY = 10,
dot_flag = false, flag = false, x = "black", y = 2, formElement, canvasLeft, canvasTop, imgData, data,
startOffsetX = 0, startOffsetY = 0;
(function () {
// Drawing canvas
drawing = document.getElementById("drawing");
drawingCtx = drawing.getContext("2d");
//Uploading and dragging images
images = new fabric.Canvas('images');
document.getElementById('imageLoader').addEventListener("change", function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({left: 0, top: 0, angle: 00,width:40, height:40}).scale(0.9);
images.add(oImg).renderAll();
var a = images.setActiveObject(oImg);
var dataURL = images.toDataURL({format: 'png', quality: 0.8});
});
};
reader.readAsDataURL(file);
});
w = drawing.width;
h = drawing.height;
//Mouse events
drawing.addEventListener("mousemove", function (e) { findxy('move', e) }, false);
drawing.addEventListener("mousedown", function (e) { findxy('down', e) }, false);
drawing.addEventListener("mouseup", function (e) { findxy('up', e) }, false);
drawing.addEventListener("mouseout", function (e) { findxy('out', e) }, false);
Drawing = document.getElementById("Drawing");
Drawing.addEventListener("click", bringDrawingToFront);
Images = document.getElementById("Images");
Images.addEventListener("click", bringImagesToFront);
imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', bringImagesToFront);
//Drawing
function findxy(res, e) {
if (res === 'down') {
prevX = currX;
prevY = currY;
currX = e.clientX - drawing.offsetLeft;
currY = e.clientY - drawing.offsetTop;
flag = true;
dot_flag = true;
if (dot_flag) {
drawingCtx.beginPath();
drawingCtx.fillStyle = x;
drawingCtx.fillRect(currX, currY, 2, 2);
drawingCtx.closePath();
dot_flag = false;
}
}
if (res === 'up' || res === "out") {
flag = false;
}
if (res === 'move') {
if (flag) {
prevX = currX;
prevY = currY;
currX = e.clientX - drawing.offsetLeft;
currY = e.clientY - drawing.offsetTop;
draw();
}
}
}
function save() {
imgData = drawingCtx.getImageData(0, 0, drawing.width, drawing.height);
}
function restore() {
drawingCtx.putImageData(imgData, 0, 0);
}
function bringDrawingToFront() {
drawing.style.zIndex = 1;
document.getElementById("images").style.zIndex = 0;
}
function bringImagesToFront() {
drawing.style.zIndex = 0;
document.getElementById("images").style.zIndex = 1;
}
//Draw lines or text
function draw() {
drawingCtx.beginPath();
drawingCtx.moveTo(prevX, prevY);
drawingCtx.lineTo(currX, currY);
drawingCtx.strokeStyle = x;
drawingCtx.lineWidth = y;
drawingCtx.stroke();
drawingCtx.closePath();
drawingCtx.fillStyle = x;
drawingCtx.font = "Italic Bold 14pt Times, serif";
drawingCtx.fillText(message, prevX, prevY);
save();
}
})();
</script>

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

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";
}
});

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

Optimize canvas drawing to make a continuous path

This is a script for filling canvas' grid squares with red color.
I'm looking for tips how to optimize my script to fill squares continuously, without chopping like here:
I tried to separate and merge some functions, but can't find a solution.
Here's the updated jsFiddle and my code:
HTML:
<canvas id="plan" width="501px" height="301px"></canvas>
JavaScript (updated):
var canvas = document.getElementById('plan');
var context = canvas.getContext('2d'),
wt = canvas.width,
ht = canvas.height;
var down = false;
var draw = function (e) {};
window.onload = grid();
var oldPos = {
mX: 0,
mY: 0
};
var dPos = {
mX: 0,
mY: 0
};
var curPos = {
mX: 0,
mY: 0
};
draw.to = function (X, Y) {
oldPos = getMousePos(canvas, e); //update position
var mposX = X,
mposY = Y;
mposX = mposX - mposX % 5;
mposY = mposY - mposY % 5;
context.fillStyle = "red";
context.fillRect(mposX + 0.5, mposY + 0.5, 5, 5);
};
draw.single = function (e) {
oldPos = getMousePos(canvas, e);
var mpos = getMousePos(canvas, e);
mpos.mX = mpos.mX - mpos.mX % 5;
mpos.mY = mpos.mY - mpos.mY % 5;
context.fillStyle = "red";
context.fillRect(mpos.mX + 0.5, mpos.mY + 0.5, 5, 5);
};
draw.move = function (e) {
if (down) {
curPos = getMousePos(canvas, e);
dPos.mX = Math.abs(curPos.mX - oldPos.mX); // distance between old & new (delta X)
dPos.mY = Math.abs(curPos.mY - oldPos.mY); // delta Y
if (dPos.mX >= 5 || dPos.mY >= 5) { // if the distance is bigger than 5px hz OR 5px vertical
lightIntermediateSquares(oldPos.mX, oldPos.mY, curPos.mX, curPos.mY); // ^ connect them
} else {
draw.single(e); // simple
}
}
};
draw.start = function (e) {
e.preventDefault();
down = true;
draw.single(e);
};
draw.stop = function (e) {
down = false;
};
function lightIntermediateSquares(startX, startY, endX, endY) {
for (var pct = 0; pct <= 1; pct += 0.03) {
var dx = endX - startX;
var dy = endY - startY;
var X = startX + dx * pct;
var Y = startY + dy * pct;
draw.to(X, Y); // is it okay?
}
}
function grid() {
context.strokeStyle = "#f0f0f0";
var h = 2.5,
p = 2.5;
context.strokeRect(0.5, 0.5, 5, 5);
for (i = 0; i < wt; i += p) {
p *= 2;
context.drawImage(canvas, p, 0);
}
for (i = 0; i < ht; i += h) {
h *= 2;
context.drawImage(canvas, 0, h);
}
}
function getMousePos(canvas, e) {
var rect = canvas.getBoundingClientRect();
return {
mX: e.clientX - rect.left - 1,
mY: e.clientY - rect.top - 1
};
}
canvas.addEventListener('mouseup', draw.stop, false);
canvas.addEventListener('mousedown', draw.start, false);
canvas.addEventListener('mousemove', draw.move, false);
canvas.addEventListener('mouseout', draw.stop, false);
Here's how to light the missing squares
Calculate a line between the previous mousemove and the current mousemove position.
Then walk that line using interpolation and color any grid squares that the line crosses.
// walk along a line from the last mousemove position
// to the current mousemove position.
// Then color any cells we pass over on our walk
for(var pct=0;pct<=1;pct+=0.06){
var dx = mouseX-lastX;
var dy = mouseY-lastY;
var X = parseInt(lastX + dx*pct);
var Y = parseInt(lastY + dy*pct);
if( !(X==lastForX && Y==lastForY) ){
draw.ColorCell(X,Y);
}
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/WvuHL/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var wt = canvas.width;
var ht = canvas.height;
var down = false;
var lastX=-20;
var lastY=-20;
var points=[];
var draw = function (e) {};
draw.started = false;
var count;
function interpolateLine(startX,startY,endX,endY){
var lastForX;
var lastForY;
//
for(var pct=0;pct<=1;pct+=0.06){
var dx = endX-startX;
var dy = endY-startY;
var X = startX + dx*pct;
var Y = startY + dy*pct;
if( !(X==lastForX && Y==lastForY) ){
draw.ColorCell(X,Y);
}
lastForX=X;
lastForY=Y;
}
}
draw.ColorCell=function(x,y){
var rw = x - 1;
var rh = y - 1;
rw = rw - rw % 5 + 0.5;
rh = rh - rh % 5 + 0.5;
context.fillStyle = "red";
context.fillRect( rw, rh, 5, 5);
};
draw.single = function (e) {
var mouseX=parseInt(e.clientX-offsetX);
var mouseY=parseInt(e.clientY-offsetY);
draw.ColorCell(mouseX,mouseY);
};
// mousemove
draw.move = function (e) {
if(!down){return;}
// get the current mouse position
var mouseX=parseInt(e.clientX-offsetX);
var mouseY=parseInt(e.clientY-offsetY);
// if we haven't moved off this XY, then don't bother processing further
if(mouseX==lastX && mouseY==lastY){return;}
// When running the for-loop below,
// many iterations will not find a new grid-cell
// so lastForX/lastForY will let us skip duplicate XY
var lastForX=lastX;
var lastForY=lastY;
// walk along a line from the last mousemove position
// to the current mousemove position.
// Then color any cells we pass over on our walk
for(var pct=0;pct<=1;pct+=0.06){
var dx = mouseX-lastX;
var dy = mouseY-lastY;
var X = parseInt(lastX + dx*pct);
var Y = parseInt(lastY + dy*pct);
if( !(X==lastForX && Y==lastForY) ){
draw.ColorCell(X,Y);
}
lastForX=X;
lastForY=Y;
}
// set this mouse position as starting position for next mousemove
lastX=mouseX;
lastY=mouseY;
};
// mousedown
draw.start = function (e) {
e.preventDefault();
lastX=parseInt(e.clientX-offsetX);
lastY=parseInt(e.clientY-offsetY);
down = true;
};
// mouseup
draw.stop = function (e) {
e.preventDefault();
down = false;
};
function grid() {
context.strokeStyle = "#f0f0f0";
var h = 2.5;
var p = 2.5;
context.strokeRect(0.5, 0.5, 5, 5);
for (i = 0; i < wt; i += p) {
p *= 2;
context.drawImage(canvas, p, 0);
}
for (i = 0; i < ht; i += h) {
h *= 2;
context.drawImage(canvas, 0, h);
}
}
canvas.addEventListener('mouseup', draw.stop, false);
canvas.addEventListener('mouseout', draw.stop, false);
canvas.addEventListener('mousedown', draw.start, false);
canvas.addEventListener('click', draw.single, false);
canvas.addEventListener('mousemove', draw.move, false);
grid();
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=501 height=301></canvas>
</body>
</html>

Categories

Resources