电话间隙画布触摸事件



我在尝试使用触摸事件的画布元素上绘制时遇到了一点问题。正在发生的事情是我恢复了页面X和页面Y,但它们似乎不正确。正如您在图像中看到的,我单击了红点所在的位置,但坐标是黑色矩形的位置。

图像

我提供的代码不是我的,我已经做了一些代码,但问题是相同的,我在联想Tab3 7,小米Mi5和三星S8上尝试过,结果总是相同的。

那么请谁能帮我解决这个问题?

[编辑] 当我从上到下触摸时,黑色指针离触摸点越来越远,然后我把它放在顶部,它到达触摸点。

var can, ctx, canX, canY, mouseIsDown = 0;

function init() {
can = document.getElementById("canvas");
ctx = can.getContext("2d");

can.addEventListener("mousedown", mouseDown, false);
can.addEventListener("mousemove", mouseXY, false);
can.addEventListener("touchstart", touchDown, false);
can.addEventListener("touchmove", touchXY, true);
can.addEventListener("touchend", touchUp, false);

document.body.addEventListener("mouseup", mouseUp, false);
document.body.addEventListener("touchcancel", touchUp, false);
}

function mouseUp() {
mouseIsDown = 0;
mouseXY();
}

function touchUp() {
mouseIsDown = 0;
// no touch to track, so just show state
showPos();
}

function mouseDown() {
mouseIsDown = 1;
mouseXY();
}

function touchDown() {
mouseIsDown = 1;
touchXY();
}

function mouseXY(e) {
if (!e)
var e = event;
canX = e.pageX - can.offsetLeft;
canY = e.pageY - can.offsetTop;
showPos();
}

function touchXY(e) {
if (!e)
var e = event;
e.preventDefault();
canX = e.targetTouches[0].pageX - can.offsetLeft;
canY = e.targetTouches[0].pageY - can.offsetTop;
showPos();
}

function showPos() {
// large, centered, bright green text
ctx.font = "24pt Helvetica";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "rgb(64,255,64)";
var str = canX + ", " + canY;
if (mouseIsDown)
str += " down";
if (!mouseIsDown)
str += " up";
ctx.clearRect(0, 0, can.width, can.height);
// draw text at center, max length to fit on canvas
ctx.fillText(str, can.width / 2, can.height / 2, can.width - 10);
// plot cursor
ctx.fillStyle = "black";
ctx.fillRect(canX -5, canY -5, 10, 10);
}

已经找到了。

真正的问题是我用CSS设置宽度和高度。 有需要填充的宽度和高度属性。

然后只需在触摸事件上执行此操作

function funcName(e){
let rect = canvas.getBoundingClientRect();
context.fillRect(e.touches[0].pageX - rect.left, e.touches[0].pageY - rect.top, 10, 10);
}

希望我解决的问题对任何人都有帮助。

最新更新