Disable Scrolling on mobile while drawing on canvas? - javascript

I'm making a site, where you can draw on a HTML5 canvas, with the mouse or on mobile with touch.
But on mobile you scroll the site while you are drawing. Thats make the drawing very uncomfortable.I've tried that, but it doesn't work:
canvas.addEventListener("touchstart", function (e) {
var mousePos = getTouchPos(canvas, e);
var touch = e.touches[0];
var mouseEvent = new MouseEvent("mousedown", {
clientX: touch.clientX,
clientY: touch.clientY
});
canvas.dispatchEvent(mouseEvent);
if (e.target.tag == canvas) {
e.preventDefault();
}
}, false);
canvas.addEventListener("touchend", function (e) {
var mouseEvent = new MouseEvent("mouseup", {});
canvas.dispatchEvent(mouseEvent);
if (e.target.tag == canvas) {
e.preventDefault();
}
}, false);
canvas.addEventListener("touchmove", function (e) {
var touch = e.touches[0];
var mouseEvent = new MouseEvent("mousemove", {
clientX: touch.clientX,
clientY: touch.clientY
});
canvas.dispatchEvent(mouseEvent);
if (e.target.tag == canvas) {
e.preventDefault();
}
}, false);
Do you have any idea, how I can avoid scrolling on mobile, when you draw on canvas?
Thank you!

Related

Camera Video Stream is being inactive/disable on implementing Drag and Drop

We have setup a video call with webrtc and we have implemented drag and drop to swap/change the user's position with HTML and JavaScript.
var dragSrcEl = null;
function handleDragStart(e) {
this.style.opacity = '0.4';
dragSrcEl = this;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', this.innerHTML);
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault();
}
e.dataTransfer.dropEffect = 'move';
return false;
}
function handleDragEnter(e) {
this.classList.add('over');
}
function handleDragLeave(e) {
this.classList.remove('over');
}
function handleDrop(e) {
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
if (dragSrcEl != this) {
dragSrcEl.innerHTML = this.innerHTML;
this.innerHTML = e.dataTransfer.getData('text/html');
}
return false;
}
function handleDragEnd(e) {
this.style.opacity = '1';
items.forEach(function (item) {
item.classList.remove('over');
});
}
let items = document.querySelectorAll('#video .streamDiv');//your specific html element ID and CLASS.
console.log("items: in test "+items)
for (var i = 0, element; (element = items[i]); i++) {
console.log("element: ",element);
element.addEventListener('dragstart', handleDragStart, false);
element.addEventListener('dragenter', handleDragEnter, false);
element.addEventListener('dragover', handleDragOver, false);
element.addEventListener('dragleave', handleDragLeave, false);
element.addEventListener('drop', handleDrop, false);
element.addEventListener('dragend', handleDragEnd, false);
}
The drag and drop is working fine whatever content like image or static video is in it, issue is (not working with webrtc) that while swapping/changing is happening with camera video feed whenever a new user is joining in with their camera feed ,then camera video feed got inactive or closed.
Take reference of our concerned issue from following video link:
https://drive.google.com/file/d/1Uw7viN_ELOOAUyeQcuGV3iS_rKe1QUL_/view?usp=sharing
Any advice? Thanks!

How can we force canvas to stay still

How can one force a canvas to remain still while you draw on it on android phones?
We have a project in Ionic, where the below code is used to allow the end user to draw on a canvas element, but when he starts drawing, the page scrolls with him.
Strange enough though, the code stops the form from scrolling up and down if the user drags left or right, but if they move their finger up or down before going left or right, the page scrolls with their draw movements, and they end up with basically nothing being drawn...
Does anybody see how I can force the scrolling to hold while the user draw's on the canvas?
//employer_signature_canvas setup
var employer_signature_canvas = document.getElementById("employer_my_canvas");
var ctx = employer_signature_canvas.getContext("2d");
ctx.strokeStyle = "#222222";
ctx.lineWith = 2;
// Set up mouse events for drawing
var drawing = false;
var mousePos = { x:0, y:0 };
var lastPos = mousePos;
employer_signature_canvas.addEventListener("mousedown", function (e) {
drawing = true;
lastPos = getMousePos(employer_signature_canvas, e);
}, false);
employer_signature_canvas.addEventListener("mouseup", function (e) {
drawing = false;
}, false);
employer_signature_canvas.addEventListener("mousemove", function (e) {
mousePos = getMousePos(employer_signature_canvas, e);
}, false);
// Get the position of the mouse relative to the employer_signature_canvas
function getMousePos(employer_signature_canvasDom, mouseEvent) {
var rect = employer_signature_canvasDom.getBoundingClientRect();
return {
x: mouseEvent.clientX - rect.left,
y: mouseEvent.clientY - rect.top
};
}
// Get a regular interval for drawing to the screen
window.requestAnimFrame = (function (callback) {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimaitonFrame ||
function (callback) {
window.setTimeout(callback, 1000/60);
};
})();
// Draw to the employer_signature_canvas
function renderemployer_signature_canvas() {
if (drawing) {
ctx.moveTo(lastPos.x, lastPos.y);
ctx.lineTo(mousePos.x, mousePos.y);
ctx.stroke();
lastPos = mousePos;
}
}
// Allow for animation
(function drawLoop () {
requestAnimFrame(drawLoop);
renderemployer_signature_canvas();
})();
// Set up touch events for mobile, etc
employer_signature_canvas.addEventListener("touchstart", function (e) {
mousePos = getTouchPos(employer_signature_canvas, e);
var touch = e.touches[0];
var mouseEvent = new MouseEvent("mousedown", {
clientX: touch.clientX,
clientY: touch.clientY
});
employer_signature_canvas.dispatchEvent(mouseEvent);
}, false);
employer_signature_canvas.addEventListener("touchend", function (e) {
var mouseEvent = new MouseEvent("mouseup", {});
employer_signature_canvas.dispatchEvent(mouseEvent);
}, false);
employer_signature_canvas.addEventListener("touchmove", function (e) {
var touch = e.touches[0];
var mouseEvent = new MouseEvent("mousemove", {
clientX: touch.clientX,
clientY: touch.clientY
});
employer_signature_canvas.dispatchEvent(mouseEvent);
}, false);
// Get the position of a touch relative to the employer_signature_canvas
function getTouchPos(employer_signature_canvasDom, touchEvent) {
var rect = employer_signature_canvasDom.getBoundingClientRect();
return {
x: touchEvent.touches[0].clientX - rect.left,
y: touchEvent.touches[0].clientY - rect.top
};
}
// Prevent scrolling when touching the employer_signature_canvas
document.body.addEventListener("touchstart", function (e) {
if (e.target == employer_signature_canvas) {
e.preventDefault();
}
}, false);
document.body.addEventListener("touchend", function (e) {
if (e.target == employer_signature_canvas) {
e.preventDefault();
}
}, false);
document.body.addEventListener("touchmove", function (e) {
if (e.target == employer_signature_canvas) {
e.preventDefault();
}
}, false);
In your template (ionic page) you can use css to remove bounce and rubberband effects:
<ion-content no-bounce class="no-scroll"><ion-content>
in your scss:
.no-scroll .scroll-content {
overflow: hidden;
float: none;
}

Interactive Graphics with PixiJS - mouseover doesn't fire, while click does

Trying to fire events when hovering over Graphics element.
click event works as expected, but mouseover does not seem to fire.
Here's excerpt with fiddlejs link:
var renderer = PIXI.autoDetectRenderer(500, 500, null, true);
var stage = new PIXI.Stage(0xFFFFFF);
stage.interactive = true;
document.getElementById("canvas").appendChild(renderer.view);
var rect = new PIXI.Graphics();
rect.lineStyle(1, 0x000);
rect.interactive = true;
rect.hitArea = new PIXI.Rectangle(0,0, 200, 200);
rect.drawRect(0,0, 200,200);
rect.click = function(ev) { console.log("clicked"); }
rect.mouseover = function(ev) { console.log("over"); }
stage.addChild(rect);
renderer.render(stage);
FiddleJS link:
http://jsfiddle.net/anps0abt/
Maybe I should use sprites instead of Graphics elements?
Thanks!
PIXI.InteractionManager handles mouseover and mouseout events in its update() function. You need to continuously update the renderer each frame in order to get a response from those events
var renderer = PIXI.autoDetectRenderer(500, 500, null, true);
var stage = new PIXI.Stage(0xFFFFFF);
stage.interactive = true;
document.getElementById("canvas").appendChild(renderer.view);
var rect = new PIXI.Graphics();
rect.lineStyle(1, 0x000);
rect.interactive = true;
rect.hitArea = new PIXI.Rectangle(0,0, 200, 200);
rect.drawRect(0,0, 200,200);
rect.click = function(ev) { console.log("clicked"); }
rect.mouseover = function(ev) { console.log("over"); }
stage.addChild(rect);
update();
function update(){
requestAnimFrame(update);
renderer.render(stage);
};
http://jsfiddle.net/anps0abt/3/

Generating new canvas dynamically in javascript

I have a canvas that I can draw things what I want to do is generate new canvases dynamically when clicking a button.I've defined a generate function but it did not work
here is script
//<![CDATA[
window.addEventListener('load', function () {
// get the canvas element and its context
var canvas = document.getElementById('sketchpad');
var context = canvas.getContext('2d');
// create a drawer which tracks touch movements
var drawer = {
isDrawing: false,
touchstart: function (coors) {
context.beginPath();
context.moveTo(coors.x, coors.y);
this.isDrawing = true;
},
touchmove: function (coors) {
if (this.isDrawing) {
context.lineTo(coors.x, coors.y);
context.stroke();
}
},
touchend: function (coors) {
if (this.isDrawing) {
this.touchmove(coors);
this.isDrawing = false;
}
}
};
// create a function to pass touch events and coordinates to drawer
function draw(event) {
var type = null;
// map mouse events to touch events
switch(event.type){
case "mousedown":
event.touches = [];
event.touches[0] = {
pageX: event.pageX,
pageY: event.pageY
};
type = "touchstart";
break;
case "mousemove":
event.touches = [];
event.touches[0] = {
pageX: event.pageX,
pageY: event.pageY
};
type = "touchmove";
break;
case "mouseup":
event.touches = [];
event.touches[0] = {
pageX: event.pageX,
pageY: event.pageY
};
type = "touchend";
break;
}
// touchend clear the touches[0], so we need to use changedTouches[0]
var coors;
if(event.type === "touchend") {
coors = {
x: event.changedTouches[0].pageX,
y: event.changedTouches[0].pageY
};
}
else {
// get the touch coordinates
coors = {
x: event.touches[0].pageX,
y: event.touches[0].pageY
};
}
type = type || event.type
// pass the coordinates to the appropriate handler
drawer[type](coors);
}
// detect touch capabilities
var touchAvailable = ('createTouch' in document) || ('ontouchstart' in window);
// attach the touchstart, touchmove, touchend event listeners.
if(touchAvailable){
canvas.addEventListener('touchstart', draw, false);
canvas.addEventListener('touchmove', draw, false);
canvas.addEventListener('touchend', draw, false);
}
// attach the mousedown, mousemove, mouseup event listeners.
else {
canvas.addEventListener('mousedown', draw, false);
canvas.addEventListener('mousemove', draw, false);
canvas.addEventListener('mouseup', draw, false);
}
// prevent elastic scrolling
document.body.addEventListener('touchmove', function (event) {
event.preventDefault();
}, false); // end body.onTouchMove
}, false); // end window.onLoad
function generate(){
var newCanvas = document.createElement('canvas');
newCanvas.width = 400;
newCanvas.height = 400;
document.getElementById('container').appendChild(newCanvas);
ctx = newCanvas.getContext('2d');
}
//]]>
here is jsfiddle http://jsfiddle.net/regeme/WVUwn/
ps:drawing not displayed on jsfiddle however it works on my localhost I have totally no idea about it , anyway what I need is generate function , I did but I think I am missing something..
Any ideas? thanks..
Below is a function I wrote to dynamically create canvas.
If the canvas already exists (same ID) then that canvas is returned.
The pixelRatio parameter can be defaulted to 1. It's used for setting the correct size on retina displays (so for iPhone with Retina the value would be 2)
function createLayer(sizeW, sizeH, pixelRatio, id, zIndex) {
// *** An id must be given.
if (typeof id === undefined) {
return false;
}
// *** If z-index is less than zero we'll make it a buffer image.
isBuffer = (zIndex < 0) ? true : false;
// *** If the canvas exist, clean it and just return that.
var element = document.getElementById(id);
if (element !== null) {
return element;
}
// *** If no zIndex is passed in then default to 0.
if (typeof zIndex === undefined || zIndex < 0) {
zIndex = 0;
}
var canvas = document.createElement('canvas');
canvas.width = sizeW;
canvas.height = sizeH;
canvas.id = id;
canvas.style.width = sizeW*pixelRatio + "px";
canvas.style.height = sizeH*pixelRatio + "px";
canvas.style.position = "absolute";
canvas.style.zIndex = zIndex;
if (!isBuffer) {
var body = document.getElementsByTagName("body")[0];
body.appendChild(canvas);
}
return canvas;
}
Change the jsfiddle option
"onLoad"
to
"No Wrap - in <body>"
EDIT: See also similar question over here: Uncaught ReferenceError for a function defined in an onload function
JSFiddle options: http://doc.jsfiddle.net/basic/introduction.html#frameworks-and-extensions
This is the working update of your JSFIDDLE
javascript:
document.getElementById('generate').addEventListener('mousedown', generate, false);
I guess this is what you want.
I've just added an eventListener to your button in javascript code itself.
P.S.: I've also added black background color to canvas to show it on white background.

Add Mouse Events for Canvas Drawing

I need to add mouse event via Javascript to below code... I have already added touch events in order to test in desktop browsers I need to add mouse events .. I tried adding mouse event to addEventListener but seems to not work I'm not pretty sure what was wrong...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=768px, maximum-scale=1.0" />
<title>rsaCanvas</title>
<script type="text/javascript" charset="utf-8">
window.addEventListener('load',function(){
// get the canvas element and its context
var canvas = document.getElementById('rsaCanvas');
var insertImage = document.getElementById('insert');
var context = canvas.getContext('2d');
//load image and annotation method
var loadData = {
imageLoad: function(){
var img = new Image();
img.src = 'the_scream.jpg';
context.drawImage(img,0,0);
}
};
// create a drawer which tracks touch movements
var drawer = {
isDrawing: false,
touchstart: function(coors){
context.beginPath();
context.moveTo(coors.x, coors.y);
this.isDrawing = true;
},
touchmove: function(coors){
if (this.isDrawing) {
context.lineTo(coors.x, coors.y);
context.stroke();
}
},
touchend: function(coors){
if (this.isDrawing) {
this.touchmove(coors);
this.isDrawing = false;
}
}
};
// create a function to pass touch events and coordinates to drawer
function draw(event){
// get the touch coordinates
var coors = {
x: event.targetTouches[0].pageX,
y: event.targetTouches[0].pageY
};
// pass the coordinates to the appropriate handler
drawer[event.type](coors);
}
// attach the touchstart, touchmove, touchend event listeners.
canvas.addEventListener('touchstart',draw, false);
canvas.addEventListener('touchmove',draw, false);
canvas.addEventListener('touchend',draw, false);
insertImage.addEventListener('click',loadData.imageLoad, false);
// prevent elastic scrolling
document.body.addEventListener('touchmove',function(event){
event.preventDefault();
},false); // end body.onTouchMove
},false); // end window.onLoad
</script>
<style>
#rsaCanvas{border:5px solid #000;}
</style>
</head>
<body>
<div id="container">
<canvas id="rsaCanvas" width="400" height="500">
Sorry, your browser is not supported.
</canvas>
<button id="insert">Insert Image</button>
</div>
</body>
</html>
try this one.
function init () {
// ...
// Attach the mousemove event handler.
canvas.addEventListener('mousemove', ev_mousemove, false);
}
// The mousemove event handler.
var started = false;
function ev_mousemove (ev) {
var x, y;
// Get the mouse position relative to the canvas element.
if (ev.layerX || ev.layerX == 0) { // Firefox
x = ev.layerX;
y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) { // Opera
x = ev.offsetX;
y = ev.offsetY;
}
// The event handler works like a drawing pencil which tracks the mouse
// movements. We start drawing a path made up of lines.
if (!started) {
context.beginPath();
context.moveTo(x, y);
started = true;
} else {
context.lineTo(x, y);
context.stroke();
}
}
source http://dev.opera.com/articles/view/html5-canvas-painting/
if your problem is with insertImage.addEventListener('click',loadData.imageLoad, false); not showing image when u click, it is because
imageLoad: function(){
var img = new Image();
img.src = 'the_scream.jpg';
context.drawImage(img,0,0);
}
Note img.src is async, to draw the image do
img.onload = (function() {
var image = img;
return function() {context.drawImage(image, 0, 0);};
})();

Categories