my code takes a mouse position. Mobile browser supports html5. but cannot use MouseUp mouseDown how can i fix it?
<!DOCTYPE HTML>
<html>
<head>
<body style="background-color:3F6E6F;">
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="1200" height="1000" onmousedown="mouseDown()" onmouseup="mouseUp()"></canvas>
<p id="demo"></p>
<script>
var depx = 0;
var depy = 0;
var flag = 0;
function writeMessage(canvas, message) {
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
context.font = '18pt Calibri';
context.fillStyle = 'black';
context.fillText(message, 10, 25);
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
function mouseDown() {
canvas.addEventListener("mousemove", myFunction);
}
function myFunction(evt) {
var mousePos = getMousePos(canvas, evt);
if (flag == 0) {
depx = mousePos.x;
depy = mousePos.y;
}
flag = 1;
var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y + ' abs position ' + (mousePos.x - depx) + ',' + (mousePos.y - depy);
writeMessage(canvas, message);
}
function mouseUp() {
flag = 0;
canvas.removeEventListener("mousemove", myFunction);
}
</script>
</body>
</html>
Here is the Html and Css code, please have a look and help me with some changes if you find any that would help.
Because touch events are not mouse events. If you add a mouse, you could get mouse events.
For touch events, you need to use
pointerup
pointerdown
events/eventlistener. Read more about pointerup and pointerdown.
Usage: Add addEventListener for pointer as well.
document.getElementById('elem1').addEventListener('pointerdown', methodForPointerDown, false);
document.getElementById('elem1').addEventListener('pointerup', methodForPointerUp, false);
There is an alternative for MouseUp and mouseDown for mobile browsers sice they dont use a mouse.
You can use touchstart and touchend instead of them in your case for a mobile browser.
There is a link here for reference
Here is another set of event listeners for mobile devices.
Pointer Events
Here is an example how you detect the pointer device type with pointer event listeners
Detecting the type of input from a user
window.addEventListener("pointerdown", detectInputType, false);
function detectInputType(event) {
switch(event.pointerType) {
case "mouse":
/* mouse input detected */
break;
case "pen":
/* pen/stylus input detected */
break;
case "touch":
/* touch input detected */
break;
default:
/* pointerType is empty (could not be detected)
or UA-specific custom type */
}
}
Hope this helps you..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With