кузьмич кузьмич - 4 days ago 9
HTML Question

whу (MouseUp mouseDown) are nоt wоrking оn mоbile browser?

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.
Thank you.

Answer

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);
Comments