Custom sizing tool is not working in Canvas Drawing - javascript

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

Related

Get image data from canvas

I'm trying to add a signature feature to a web app. Users should have the possibility to sign with a pencil on a touch screen device. I'm using HTML5 canvas, JavaScript and PHP to get things done. I found a script for both mouse and touch support.
The drawing on the canvas works fine. When I submit the form, the scribble will get cropped properly (so it seems). But the generated base64-png data (saved in a database) is an empty image.
Here's the JS code I'm using:
var canvas, ctx;
var mouseX, mouseY, mouseDown = 0;
var touchX, touchY;
var lastX, lastY = -1;
canvas = document.getElementById('scribble-canvas');
ctx = canvas.getContext('2d');
canvas.addEventListener('mousedown', scribbleMouseDown, false);
canvas.addEventListener('mousemove', scribbleMouseMove, false);
canvas.addEventListener('mouseup', scribbleMouseUp, false);
canvas.addEventListener('touchstart', scribbleTouchStart, false);
canvas.addEventListener('touchend', scribbleTouchEnd, false);
canvas.addEventListener('touchmove', scribbleTouchMove, false);
function drawLine(ctx, x, y, size) {
if (lastX == -1) {
lastX = x;
lastY = y;
}
ctx.strokeStyle = "#000000";
ctx.lineCap = "round";
ctx.lineWidth = size;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.stroke();
ctx.closePath();
lastX = x;
lastY = y;
}
function scribbleMouseDown() {
mouseDown = 1;
drawLine(ctx, mouseX, mouseY, 3);
}
function scribbleMouseUp() {
mouseDown = 0;
lastX = -1;
lastY = -1;
}
function scribbleMouseMove(e) {
getMousePos(e);
if (mouseDown == 1) {
drawLine(ctx, mouseX, mouseY, 3);
}
}
function getMousePos(e) {
if ( ! e) {
var e = event;
}
if (e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if (e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
}
function scribbleTouchStart() {
getTouchPos();
drawLine(ctx, touchX, touchY, 3);
event.preventDefault();
}
function scribbleTouchEnd() {
lastX = -1;
lastY = -1;
}
function scribbleTouchMove(e) {
getTouchPos(e);
drawLine(ctx, touchX, touchY, 3);
event.preventDefault();
}
function getTouchPos(e) {
if ( ! e) {
var e = event;
}
if (e.touches) {
if (e.touches.length == 1) {
var touch = e.touches[0];
touchX = touch.pageX - touch.target.offsetLeft;
touchY = touch.pageY - touch.target.offsetTop;
}
}
}
function crop(canvas) {
var w = canvas.width, h = canvas.height;
var pix = {x:[], y:[]};
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var x, y, index;
for (y = 0; y < h; y++) {
for (x = 0; x < w; x++) {
index = (y * w + x) * 4;
if (imageData.data[index+3] > 0) {
pix.x.push(x);
pix.y.push(y);
}
}
}
pix.x.sort(function(a,b){return a-b});
pix.y.sort(function(a,b){return a-b});
var n = pix.x.length-1;
w = 1 + pix.x[n] - pix.x[0];
h = 1 + pix.y[n] - pix.y[0];
var cut = ctx.getImageData(pix.x[0], pix.y[0], w, h);
document.body.style.opacity = 0;
canvas.width = w;
canvas.height = h;
ctx.putImageData(cut, 0, 0);
return canvas.toDataURL();
}
On the PHP side I just pick the data returned by the crop() function and save it to the database.
What I tried so far is to strip off the touch support to see if it works just on mouse devices.
Additional code as suggested by user traktor:
The following jQuery code submits the form with the image data to the PHP script:
$(document).on('click', '#scribble-submit', function(e) {
e.preventDefault();
var btn = $(this);
var data = crop(document.querySelector('#scribble-canvas'));
$.post('/scribble/ax/ins_scribble', $('#form-scribble').serialize() + '&data=' + data, function(ans) {
window.location.href = '/' + btn.data('redirect');
});
});
The PHP part looks like this (using the CI3 framework):
$post = $this->input->post();
$this->db->where('id', $id);
$this->db->update('personen', ['signatur' => $post['data']]);
echo TRUE;
So far, jQuery and PHP works fine. The data is successfully inserted into the database. The LONGBLOB field contains this code:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMQAAAC3CAYAAABNEPEEAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAxKADAAQAAAABAAAAtwAAAAB1wSLaAAAYVElEQVR4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CfwSPA3Mfx9OIX40CCkZA PxV3uYrDAkZ1KKQoe6RRoffA94f81vhZo1ihYBEsouj0CAFYxb0IvSRdDndLSafBTQf N8CpifPpxP/BlgfRASDLRdDQf6HpMVklkF4GQPfDgdvOT8Mv8UaszwU6AxxBogJBjowYAqgRUYVY77wOQeZ2T3YASm6eMIGhfo/Y6HgMZD5k8yPIDfQoKBARlQN0mVwrcUz3CsreELgyyKFhIPAb8BL4Bkwbfjm/jte0CtRnzsCxIaLQs1OsEMpXcDtuhFeC8zONCClLYpqOC9AV4FzRR9b3YloLfM1MVZE2wOVgOLgb5EXcHvgsf6 jHiGsdAkSuECtu2QN0K9a/7kueJfB10gjOB unqovhFPg5rFj3FVQGWA5uCbcCEik7QrzzOL 8C2SO7bgPxjgckpC1FrhDGnQrh5WCsRQwSvs3vmtNXRVEhHAPeB3oLr69CqXRXAZoO1bWqTCuApcDKQDNE/T35 amH/Iij88GcHrFx0DQGylAhROYOQPPyS4M3gQrwSkCFvRXydzLVgPn2SqgK CCQbSEtZKAsFaIvilUp1J05HuhJLi70HnEaMp9E9dRXq6MB/oUgvgwCCVmTMleI5L1Qt2Y0sO7Oiujq73eAYWCwLpOe hqsa5pXT3oV/rcqoSrEeyAk4wz8P tCAtne45WMAAAAAElFTkSuQmCC
Using this data as an image source for the img tag results in the empty image.
The problem is this jQuery line:
$.post('/scribble/ax/ins_scribble', $('#form-scribble').serialize() + '&data=' + data, function(ans) {
Combining the serialize function and an addition of &data= didn't work. So I changed it to:
$.post('/scribble/ax/ins_scribble', { data: data }, function(ans) {
You code runs fine:
var canvas, ctx;
var mouseX, mouseY, mouseDown = 0;
var touchX, touchY;
var lastX, lastY = -1;
canvas = document.getElementById('scribble-canvas');
ctx = canvas.getContext('2d');
canvas.addEventListener('mousedown', scribbleMouseDown, false);
canvas.addEventListener('mousemove', scribbleMouseMove, false);
canvas.addEventListener('mouseup', scribbleMouseUp, false);
canvas.addEventListener('touchstart', scribbleTouchStart, false);
canvas.addEventListener('touchend', scribbleTouchEnd, false);
canvas.addEventListener('touchmove', scribbleTouchMove, false);
function drawLine(ctx, x, y, size) {
if (lastX == -1) {
lastX = x;
lastY = y;
}
ctx.strokeStyle = "#000000";
ctx.lineCap = "round";
ctx.lineWidth = size;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.stroke();
ctx.closePath();
lastX = x;
lastY = y;
}
function scribbleMouseDown() {
mouseDown = 1;
drawLine(ctx, mouseX, mouseY, 3);
}
function scribbleMouseUp() {
mouseDown = 0;
lastX = -1;
lastY = -1;
}
function scribbleMouseMove(e) {
getMousePos(e);
if (mouseDown == 1) {
drawLine(ctx, mouseX, mouseY, 3);
}
}
function getMousePos(e) {
if (!e) {
var e = event;
}
if (e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
} else if (e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
}
function scribbleTouchStart() {
getTouchPos();
drawLine(ctx, touchX, touchY, 3);
event.preventDefault();
}
function scribbleTouchEnd() {
lastX = -1;
lastY = -1;
}
function scribbleTouchMove(e) {
getTouchPos(e);
drawLine(ctx, touchX, touchY, 3);
event.preventDefault();
}
function getTouchPos(e) {
if (!e) {
var e = event;
}
if (e.touches) {
if (e.touches.length == 1) {
var touch = e.touches[0];
touchX = touch.pageX - touch.target.offsetLeft;
touchY = touch.pageY - touch.target.offsetTop;
}
}
}
function crop(canvas) {
var w = canvas.width,
h = canvas.height;
var pix = {
x: [],
y: []
};
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var x, y, index;
for (y = 0; y < h; y++) {
for (x = 0; x < w; x++) {
index = (y * w + x) * 4;
if (imageData.data[index + 3] > 0) {
pix.x.push(x);
pix.y.push(y);
}
}
}
pix.x.sort(function(a, b) {
return a - b
});
pix.y.sort(function(a, b) {
return a - b
});
if (pix.x.length == 0) {
return '#';
}
var n = pix.x.length - 1;
w = 1 + pix.x[n] - pix.x[0];
h = 1 + pix.y[n] - pix.y[0];
var cut = ctx.getImageData(pix.x[0], pix.y[0], w, h);
//document.body.style.opacity = 0;
canvas.width = w;
canvas.height = h;
ctx.putImageData(cut, 0, 0);
return canvas.toDataURL();
}
document.getElementById('scribble-submit').addEventListener('click', function(e) {
e.preventDefault();
var data = crop(document.querySelector('#scribble-canvas'));
document.getElementById('scribble-result').setAttribute('src', data);
});
<html>
<body>
<canvas id="scribble-canvas" style="width:200; height:200; border: 1px solid blue;"></canvas>
<br>
<button id="scribble-submit">
Run
</button>
<br>
Output:
<br>
<img src="#" id="scribble-result" />
</body>
</html>
You either send the wrong data or use different data to render.
If you are saving into a .png file, you may want to strip out the initial data:image/png;base64, before turning that into bytes.

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>

Canvas Quadratic Curve Changing Middle Point

I want change the middle point of canvas quadratic curve which is far away from the line while dragging middle point. On dragging i want to stick with the link as now its increasing the distance of the middle point.http://jsfiddle.net/ashishbhatt/yqgak7eq/1/
http://s25.postimg.org/hegxhlgrj/123123.jpg
Please check the above reference image for the same.
Code :
(function() {
var canvas, ctx, code, point, style, drag = null, dPoint;
// define initial points
function Init(quadratic) {
point = {
p1: { x:0, y:100 },
p2: { x:200, y:100 }
};
if (quadratic) {
point.cp1 = { x: 100, y: 50 };
}
else {
point.cp1 = { x: 100, y: 100 };
point.cp2 = { x: 100, y: 100 };
}
// default styles
style = {
curve: { width: 2, color: "#333" },
cpline: { width: 1, color: "#C00" },
point: { radius: 6, width: 1, color: "#900", fill: "rgba(200,200,200,0.5)", arc1: 0, arc2: 2 * Math.PI }
}
// line style defaults
ctx.lineCap = "round";
ctx.lineJoin = "round";
// event handlers
canvas.onmousedown = DragStart;
canvas.onmousemove = Dragging;
canvas.onmouseup = canvas.onmouseout = DragEnd;
DrawCanvas();
}
// draw canvas
function DrawCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// control lines
ctx.lineWidth = style.cpline.width;
ctx.strokeStyle = style.cpline.color;
ctx.beginPath();
//ctx.moveTo(point.p1.x, point.p1.y);
//ctx.lineTo(point.cp1.x, point.cp1.y);
if (point.cp2) {
//ctx.moveTo(point.p2.x, point.p2.y);
//ctx.lineTo(point.cp2.x, point.cp2.y);
}
else {
//ctx.lineTo(point.p2.x, point.p2.y);
}
ctx.stroke();
// curve
ctx.lineWidth = style.curve.width;
ctx.strokeStyle = style.curve.color;
ctx.beginPath();
ctx.moveTo(point.p1.x, point.p1.y);
if (point.cp2) {
//ctx.bezierCurveTo(point.cp1.x, point.cp1.y, point.cp2.x, point.cp2.y, point.p2.x, point.p2.y);
}
else {
ctx.quadraticCurveTo(point.cp1.x, point.cp1.y, point.p2.x, point.p2.y);
}
ctx.stroke();
// control points
for (var p in point) {
ctx.lineWidth = style.point.width;
ctx.strokeStyle = style.point.color;
ctx.fillStyle = style.point.fill;
ctx.beginPath();
ctx.arc(point[p].x, point[p].y, style.point.radius, style.point.arc1, style.point.arc2, true);
ctx.fill();
ctx.stroke();
}
ShowCode();
}
// show canvas code
function ShowCode() {
var myCounter = 0;
if(point.cp1.y < 100){
myCounter = point.cp1.y-100;
}else if(point.cp1.y > 100){
myCounter = point.cp1.y-100;
}
if (code) {
code.firstChild.nodeValue = myCounter
}
}
// start dragging
function DragStart(e) {
e = MousePos(e);
var dx, dy;
for (var p in point) {
//console.log(p)
//dx = point[p].x - e.x;
if(p == 'cp1'){
dy = point[p].y - e.y;
if ((dy * dy) < style.point.radius * style.point.radius) {
drag = p;
dPoint = e;
canvas.style.cursor = "move";
return;
}
}
}
}
// dragging
function Dragging(e) {
if (drag) {
e = MousePos(e);
//point[drag].x += e.x - dPoint.x;
point[drag].y += e.y - dPoint.y;
dPoint = e;
DrawCanvas();
}
}
// end dragging
function DragEnd(e) {
drag = null;
canvas.style.cursor = "default";
DrawCanvas();
}
// event parser
function MousePos(event) {
event = (event ? event : window.event);
return {
//x: event.pageX - canvas.offsetLeft,
y: event.pageY - canvas.offsetTop
}
}
// start
canvas = document.getElementById("canvasSettings");
code = document.getElementById("code");
if (canvas.getContext) {
ctx = canvas.getContext("2d");
Init(canvas.className == "quadratic");
}
})();

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