Touch move event not correct - javascript

I'm busy creating a small real time drawing app and got stuck trying to create a touchscreen system. It's partially working but when I touch and move the line connects to the last line.
Here's my code:
document.addEventListener("DOMContentLoaded", function() {
var mouse = {
click: false,
move: false,
pos: {x:0, y:0},
pos_prev: false,
colour: "blue"
};
var canvas = document.getElementById('drawing');
var ctx = canvas.getContext('2d');
var width = window.innerWidth;
var height = window.innerHeight;
var socket = io.connect();
canvas.width = width;
canvas.height = height;
/* window.onresize= function(){
var width = window.innerWidth;
var height = window.innerHeight;
console.log(height);
canvas.style.width = width;
canvas.style.height = height;
}; */
canvas.onmousedown = function(e){ mouse.click = true; };
canvas.onmouseup = function(e){ mouse.click = false; };
canvas.ontouchstart = function(e){ mouse.click = true; };
canvas.ontouchend = function(e){ mouse.click = false; };
canvas.onmousemove = function(e) {
mouse.pos.x = e.clientX / width;
mouse.pos.y = e.clientY / height;
mouse.pos.w = document.getElementById("rag").value;
mouse.move = true;
};
canvas.ontouchmove = function(e) {
var touch = e.touches[0];
var x = touch.pageX - canvas.offsetLeft;
var y = touch.pageY - canvas.offsetTop;
mouse.pos.x = x / width;
mouse.pos.y = y / height;
console.log(mouse.pos.x);
mouse.pos.w = document.getElementById("rag").value;
mouse.move = true;
};
socket.on('draw_line', function (data) {
var line = data.line;
ctx.strokeStyle = line[2];
ctx.lineWidth = line[0].w;
ctx.beginPath();
ctx.moveTo(line[0].x * width, line[0].y * height);
ctx.lineTo(line[1].x * width, line[1].y * height);
ctx.stroke();
});
socket.on('clear', function () {
ctx.clearRect(0,0,width,height);
});
function mainLoop() {
if (mouse.click && mouse.move && mouse.pos_prev) {
mouse.colour = document.getElementById("col").value;
socket.emit('draw_line', { line: [ mouse.pos, mouse.pos_prev, mouse.colour]});
mouse.move = false;
}
mouse.pos_prev = {x: mouse.pos.x, y: mouse.pos.y};
setTimeout(mainLoop, 20);
}
mainLoop();
});
A life example can be found here:
http://80.61.54.121:88/
Does anyone know how to fix the lines connecting with eacother? Thanks in advance.

Related

How to draw rectangle in canvas which is already in pdf.js

am using pdf.js here am rendering my pdf in canvas,
My code is:
<div id="viewerContainer" tabindex="0">
<div id="viewer" class="pdfViewer"></div>
</div>
The above canvas is generating through viewer.js
Now I am trying to draw rectangle on my pdf, but its not showing my rectangle,
My script is in below:
<script type="text/javascript">
var canvas, context, startX, endX, startY, endY;
var mouseIsDown = 0;
function init() {
canvas = document.getElementById("page1");
context = canvas.getContext("2d");
canvas.addEventListener("mousedown", mouseDown, false);
canvas.addEventListener("mousemove", mouseXY, false);
canvas.addEventListener("mouseup", mouseUp, false);
}
function mouseUp() {
if (mouseIsDown !== 0) {
mouseIsDown = 0;
drawSquare(); //update on mouse-up
}
}
function mouseDown() {
mouseIsDown = 1;
startX = endX = event.clientX - canvas.offsetLeft; //remember to subtract
startY = endY = event.clientY - canvas.offsetTop; //canvas offset
drawSquare(); //update
}
function mouseXY(eve) {
if (mouseIsDown !== 0) {
if (!eve) {
var eve = event;
}
endX = event.pageX - canvas.offsetLeft;
endY = event.pageY - canvas.offsetTop;
drawSquare();
}
}
function drawSquare() {
// creating a square
var width = Math.abs(startX - endX);
var height = Math.abs(startY - endY);
context.clearRect(0, 0, context.width, context.height);
//or use fillRect if you use a bg color
context.beginPath();
context.rect(startX, startY, width, height);
context.fillStyle = "yellow";
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();
}
</script>
viwer.js code:
var canvasWrapper = document.createElement('div');
canvasWrapper.style.width = div.style.width;
canvasWrapper.style.height = div.style.height;
canvasWrapper.classList.add('canvasWrapper');
if (this.annotationLayer && this.annotationLayer.div) {
div.insertBefore(canvasWrapper, this.annotationLayer.div);
} else {
div.appendChild(canvasWrapper);
}
var textLayer = null;
if (this.textLayerFactory) {
var textLayerDiv = document.createElement('div');
textLayerDiv.className = 'textLayer';
textLayerDiv.style.width = canvasWrapper.style.width;
textLayerDiv.style.height = canvasWrapper.style.height;
if (this.annotationLayer && this.annotationLayer.div) {
div.insertBefore(textLayerDiv, this.annotationLayer.div);
} else {
div.appendChild(textLayerDiv);
}
textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv, this.id - 1, this.viewport, this.enhanceTextSelection);
}
var viewport = this.viewport;
var canvas = document.createElement('canvas');
canvas.id = this.renderingId;
canvas.setAttribute('hidden', 'hidden');
var isCanvasHidden = true;
var showCanvas = function showCanvas() {
if (isCanvasHidden) {
canvas.removeAttribute('hidden');
isCanvasHidden = false;
}
};
canvasWrapper.appendChild(canvas);
Is there any mistake in my code? I have searched many source but I could not able to find the correct one. Kindly help me in this issue.

Replacing color with photo in html drawing tool

In this drawing tool for html I want to replace the color (#ddd) with a photo.
Instead of the current version I want to replace the grey rectangle with a photo. Any idea on how to do that? And it won't let me reposition the rectangle, any idea why?
(function() {
function createCanvas(parent, width, height) {
var canvas = {};
canvas.node = document.createElement('canvas');
canvas.context = canvas.node.getContext('2d');
canvas.node.width = width || 100;
canvas.node.height = height || 100;
parent.appendChild(canvas.node);
return canvas;
}
function init(container, width, height, fillColor) {
var canvas = createCanvas(container, width, height);
var ctx = canvas.context;
// define a custom fillCircle method
ctx.fillCircle = function(x, y, radius, fillColor) {
this.fillStyle = fillColor;
this.beginPath();
this.moveTo(x, y);
this.arc(x, y, radius, 0, Math.PI * 2, false);
this.fill();
};
ctx.clearTo = function(fillColor) {
ctx.fillStyle = fillColor;
ctx.fillRect(0, 0, width, height);
};
ctx.clearTo(fillColor || "#ddd");
// bind mouse events
canvas.node.onmousemove = function(e) {
if (!canvas.isDrawing) {
return;
}
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
var radius = 25; // or whatever
var fillColor = '#ff0000';
ctx.globalCompositeOperation = 'destination-out';
ctx.fillCircle(x, y, radius, fillColor);
};
canvas.node.onmousedown = function(e) {
canvas.isDrawing = true;
};
canvas.node.onmouseup = function(e) {
canvas.isDrawing = false;
};
}
var container = document.getElementById('canvas');
init(container, 400, 400, '#ddd');
})();
You can achieve this by layering a solid canvas on top of another canvas. Erasing parts of the top canvas should reveal the canvas below.
The following reuses 99% of the code from two separate posts.
Loading the image onto the canvas.
Erasing the top canvas (layer).
// Borrowed from here: https://stackoverflow.com/a/4776378
var canvasWrapper = document.getElementsByClassName('layer-wrapper')[0];
var imageLayer = canvasWrapper.querySelector('.layer-image');
var drawLayer = canvasWrapper.querySelector('.layer-draw');
var img = new Image;
img.onload = function() {
imageLayer.width = drawLayer.width = img.width;
imageLayer.height = drawLayer.height = img.height;
var imageCtx = imageLayer.getContext('2d');
imageCtx.drawImage(img, 0, 0);
var drawCtx = drawLayer.getContext('2d');
drawCtx.fillStyle = '#7F7F7F';
drawCtx.fillRect(0, 0, img.width, img.height);
};
img.src = 'https://pbs.twimg.com/profile_images/462372073982025728/jTHaxsxd.jpeg';
// Borrowed from here: https://stackoverflow.com/a/25916334
var RADIUS = 32;
var canvas = canvasWrapper.querySelector('.layer-wrapper .layer-draw');
var ctx = canvas.getContext('2d');
var lastX;
var lastY;
var strokeColor = 'red';
var strokeWidth = 5;
var mouseX;
var mouseY;
var canvasOffset = $(canvas).offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var isMouseDown = false;
function handleMouseDown(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// Put your mousedown stuff here
lastX = mouseX;
lastY = mouseY;
isMouseDown = true;
}
function handleMouseUp(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// Put your mouseup stuff here
isMouseDown = false;
}
function handleMouseOut(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// Put your mouseOut stuff here
isMouseDown = false;
}
function handleMouseMove(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// Put your mousemove stuff here
if (isMouseDown) {
ctx.beginPath();
if (mode == "pen") {
ctx.globalCompositeOperation = "source-over";
ctx.moveTo(lastX, lastY);
ctx.lineTo(mouseX, mouseY);
ctx.stroke();
} else {
ctx.globalCompositeOperation = "destination-out";
ctx.arc(lastX, lastY, RADIUS, 0, Math.PI * 2, false);
ctx.fill();
}
lastX = mouseX;
lastY = mouseY;
}
}
$(canvas).mousedown(function(e) {
handleMouseDown(e);
}).mousemove(function(e) {
handleMouseMove(e);
}).mouseup(function(e) {
handleMouseUp(e);
}).mouseout(function(e) {
handleMouseOut(e);
});
var mode = 'eraser';
//$('#pen') .click(function() { mode = 'pen'; });
//$('#eraser').click(function() { mode = 'eraser'; });
.layer-wrapper {
position: relative;
width: 400px;
height: 300px;
}
.layer-wrapper canvas.layer {
position: absolute;
top: 0;
left: 0;
}
.layer-image {
z-index: 1;
}
.layer-draw {
z-index: 100;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="layer-wrapper">
<canvas class="layer layer-image"></canvas>
<canvas class="layer layer-draw"></canvas>
</div>

Clearing drawing from Canvas permanently

I have a function that clears all drawings off of the background image in canvas when a button is clicked, but when you go to draw again, the old (previously cleared drawings) reappears. How can I make a hard delete so that I can draw again without reloading the page
'use strict';
function initCanvas() {
let bMouseIsDown = false;
let canvas = document.getElementById('cvs');
let ctx = canvas.getContext('2d');
let convert = document.getElementById('convert');
let sel = 'png';
let imgs = document.getElementById('imgs');
let imgW = 300;
let imgH = 200;
let background = new Image();
background.crossOrigin = '';
background.src = "http://i.imgur.com/yf6d9SX.jpg";
background.onload = function(){
ctx.drawImage(background,0,0,600,400);
}
bind(canvas,ctx,convert,sel,imgs,imgW,imgH,bMouseIsDown);
};
initCanvas()
function bind (canvas,ctx,convert,sel,imgs,imgW,imgH,bMouseIsDown) {
let iLastX = 0;
let iLastY = 0;
let iX;
let iY;
canvas.onmousedown = function(e) {
bMouseIsDown = true;
iLastX = e.clientX - canvas.offsetLeft + (window.pageXOffset||document.body.scrollLeft||document.documentElement.scrollLeft);
iLastY = e.clientY - canvas.offsetTop + (window.pageYOffset||document.body.scrollTop||document.documentElement.scrollTop);
}
canvas.onmouseup = function() {
bMouseIsDown = false;
iLastX = -1;
iLastY = -1;
}
canvas.onmousemove = function(e) {
if (bMouseIsDown) {
iX = e.clientX - canvas.offsetLeft + (window.pageXOffset||document.body.scrollLeft||document.documentElement.scrollLeft);
iY = e.clientY - canvas.offsetTop + (window.pageYOffset||document.body.scrollTop||document.documentElement.scrollTop);
ctx.moveTo(iLastX, iLastY);
ctx.lineTo(iX, iY);
ctx.stroke();
ctx.strokeStyle = "blue";
ctx.lineJoin = "round";
ctx.lineWidth = 5;
iLastX = iX;
iLastY = iY;
}
};
document.getElementById('clear').addEventListener('click', function() {
rerenderImg();
});
function rerenderImg() {
iY = [];
iX=[];
initCanvas()
}
};
You need to call ctx.beginPath(); before drawing on the canvas again.
The logical place to put this is just before your call to ctx.moveTo.
An explanation of why this is needed is given here.
You should actually run clearRect on the canvas:
ctx.clearRect(0, 0, canvas.width, canvas.height);

JavaScript Canvas touch future with multiple eventListeners

I need to add a touch feature to the canvas app that I'm working on (multiple users white board), and I already read about the event listeners and the event.preventDefault(), but I can't understand how can I use two event listeners with 'DOMContentLoaded' and 'touchmove'. At this point I don't know if using multiple event listeners is the solution I need.
This is the code I'm using:
document.addEventListener("DOMContentLoaded", function() {
var mouse = {
click: false,
move: false,
pos: {x:0, y:0},
pos_prev: false
};
var canvas = document.getElementById('drawing');
var context = canvas.getContext('2d');
var width = 1280;
var height = 960;
var socket = io.connect();
var lineWidth = 1;
var shadowBlur = 1;
var shadowColor = "black";
var strokeStyle = "black";
canvas.width = width;
canvas.height = height;
canvas.onmousedown = function(e){ mouse.click = true; };
canvas.onmouseup = function(e){ mouse.click = false; };
canvas.onmousemove = function(e) {
mouse.pos.x = e.clientX / width;
mouse.pos.y = e.clientY / height;
mouse.move = true;
};
socket.on('draw_line', function (data) {
var line = data.line;
context.beginPath();
context.lineWidth = lineWidth;
context.shadowBlur = shadowBlur;
context.strokeStyle = strokeStyle;
context.lineJoin="round";
context.lineCap = "round";
context.moveTo(line[0].x * width, line[0].y * height);
context.lineTo(line[1].x * width, line[1].y * height);
context.stroke();
});
function mainLoop() {
if (mouse.click && mouse.move && mouse.pos_prev) {
socket.emit('draw_line', { line: [ mouse.pos, mouse.pos_prev ] });
mouse.move = false;
}
mouse.pos_prev = {x: mouse.pos.x, y: mouse.pos.y};
setTimeout(mainLoop, 50);
}
mainLoop();
});
I would really appreciate any help.
Thanks.
Are you encountering some sort of bug? Right now it appears that your code operates by listening for the mouse being clicked and the mouse being moved. If the mouse is pressed down, the mouse is being moved and the loop has run at least once (mouse.click && mouse.move && mouse.pos_prev) then it draws a line on the canvas element.

How can I move an obj inside a canvas using touch event?

Hello everybody I've just trying to understands how this does it work
I have a basic canvas base just in javascript and I would like to move it using touch event
I'm not sure about this but Can I use the drag event ?
Do I need to use a loop function ?
How can I trigger that blue cube ?
I know there are lot of javascript engine in fact i'm using phaser but I would like to undertand this
Thank you
var canvas, cx, width, height;
var cube = {
x: 80,
y: 100,
update: function () {
},
draw: function (ctx) {
ctx.save();
ctx.fillStyle = "blue";
ctx.fillRect(100, 410, 50, 50);
ctx.restore();
}
};
function onpress(e) {
e.preventDefault();
var whichArt = e.target;
var touch = e.touches[0];
var moveOffsetX = whichArt.offsetLeft - touch.pageX;
var moveOffsetY = whichArt.offsetTop - touch.pageY;
whichArt.addEventListener('touchmove', function () {
var positionX = touch.pageX + moveOffsetX;
var positionY = touch.pageY + moveOffsetY;
cube.x = positionX;
cube.y = positionY;
console.log(cube.x);
}, false);
}
function main() {
canvas = document.createElement("canvas");
width = window.innerWidth;
height = window.innerHeight;
if (width >= 500) {
width = 320;
height = 480;
canvas.style.border = "1px solid #000";
}
document.addEventListener("touchstart", onpress);
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
run();
}
function run() {
var loop = function () {
update();
render();
window.requestAnimationFrame(loop, canvas);
}
window.requestAnimationFrame(loop, canvas);
}
function update() {
}
function render() {
cube.draw(ctx);
}
main();
http://jsfiddle.net/marcogomesr/sxbo3r83/
The canvas is only a passive drawing surface : You have to handle the drag by yourself.
Below a short example :
draggables object have to implement isPointInside, and to be added to the list of draggables object.
I used a dragData object that stores the list of draggables object, the currently dragged object, maybe you'll want to store the start/current point of the drag, and handle a drag-offset so the user holds the object right on the point where he/she started dragging.
http://jsfiddle.net/3ksvn4y0/3/
var canvas, cx, width, height;
var canvasRect;
var cube1, cube2;
var dragData = {
draggables: [],
start: { x: 0, y: 0
},
current: { x: 0, y: 0
},
target: null
};
function Cube(x,y,w,h, color) {
this.x=x; this.y=y; this.w=w; this.h = h;
this.color = color;
}
Cube.prototype = {
update: function () {
},
draw: function (ctx) {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.w, this.h);
},
isPointInside: function (x, y) {
return (x >= this.x) && (x < this.x + this.w) && (y > this.y) && (y < this.y + this.h);
}
};
var pointerCoords = {
x: 0,
y: 0,
update: function (e) {
var coords = e.touches ? e.touches[0] : e;
this.x = coords.pageX - canvasRect.left;
this.y = coords.pageY - canvasRect.top;
}
};
function onStart(e) {
e.preventDefault();
pointerCoords.update(e);
// look if we start the touch within a draggable object
var target = null;
for (var i = 0; i < dragData.draggables.length; i++) {
var draggable = dragData.draggables[i];
if (draggable.isPointInside(pointerCoords.x, pointerCoords.y)) {
target = draggable;
break;
}
}
dragData.target = target;
}
function onMove(e) {
pointerCoords.update(e);
var target = dragData.target;
if (!target) return;
target.x = pointerCoords.x;
target.y = pointerCoords.y;
}
function onStop(e) {
pointerCoords.update(e);
e.preventDefault();
if (!dragData.target) return;
onMove(e);
dragData.target = null;
}
function main() {
canvas = document.createElement("canvas");
width = window.innerWidth;
height = window.innerHeight;
if (width >= 500) {
width = 320;
height = 480;
canvas.style.border = "1px solid #000";
}
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
canvasRect = canvas.getBoundingClientRect();
canvas.addEventListener("touchstart", onStart);
canvas.addEventListener('touchmove', onMove);
canvas.addEventListener("touchstop", onStop);
canvas.addEventListener("mousedown", onStart);
canvas.addEventListener('mousemove', onMove);
canvas.addEventListener("mouseup", onStop);
cube1 = new Cube(100, 80, 30, 30, 'blue');
cube2 = new Cube(150, 160, 20, 20, 'red');
dragData.draggables.push(cube1, cube2);
run();
}
function run() {
var loop = function () {
requestAnimationFrame(loop);
update();
render();
}
loop();
}
function update() {
}
function render() {
ctx.clearRect(0, 0, width, height);
cube1.draw(ctx);
cube2.draw(ctx);
}
main();

Categories

Resources