【发布时间】:2018-03-20 18:25:35
【问题描述】:
我在尝试使用触摸事件在画布元素上绘图时遇到了一点问题。发生的事情是我恢复了 pageX 和 pageY 但它们似乎不正确。正如你在图片中看到的,我点击了红点所在的位置,但坐标是黑色矩形所在的位置。
我提供的代码不是我的,我已经做了一些代码,但问题是一样的,我在联想 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);
}
【问题讨论】:
标签: javascript cordova canvas draw phonegap