- 此问题在此处已有答案**:
Disable scrolling when touch moving certain element(10个答案)
2天前关闭。
我只是想用"指针"事件在我的手机上画画。
这在我的桌面上用鼠标可以用,但在我的(安卓)手机上不行。我应该可以画曲线,但用手指在手机上拖动会导致"进入"和几次"移动",但随后就会"离开"。
它必须是在线的:https://dbarc.net/SOtest.html
<!DOCTYPE html>
<html>
<!-- works on desktop, leaves on phone (dbarc.net/SOtest.html) -->
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body { width:400px; }
#canvas { background:#eee; }
</style>
<script>
"use strict";
let canvas, ctx, xx, yy, infodiv;
window.onload = function() {
infodiv = document.getElementById("infodiv"); // info output
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
// canvas.addEventListener('pointerenter', function() { ptrEnter(); } );
canvas.addEventListener('pointerenter', ptrEnter); // better
canvas.addEventListener('pointerleave', ptrLeave);
canvas.addEventListener('pointermove', ptrMove);
}
function ptrEnter() { // shows an enter
infodiv.innerHTML += "ENTER ";
}
function ptrLeave() { // shows a leave
infodiv.innerHTML += "LEAVE ";
}
function ptrMove(ev) { // draws (no pen up/down)
infodiv.innerHTML += "m ";
let x0 = canvas.offsetLeft, y0 = canvas.offsetTop;
let xold = xx, yold = yy;
xx = Math.floor(ev.clientX) - x0;
yy = Math.floor(ev.clientY) - y0;
ctx.beginPath();
ctx.moveTo(xold,yold);
ctx.lineTo(xx, yy);
ctx.stroke();
}
</script>
</head>
<body>
<canvas id="canvas" width="400" height="300"></canvas>
<div id="infodiv">Events: </div>
</body>
</html>
1条答案
按热度按时间yr9zkbsy1#
在花了几个小时后,我找到了这个问题的正确解决方案。首先,对于非桌面设备,事件应该是touchmove*而不是“mousemove”。其次,要获得clientX和clientY的值,您必须使用event.targetTouchs[0].clientX或**.clientY***。完整代码如下所示。