我如何通过触摸控制白条来放置我的功能moveBloco()。
我想让智能手机用户可以触摸白条。通过触摸来上下移动条。
function moveBloco(){
if(87 in keyBoard && left.y > 0)
left.y -= left.speed;
if(83 in keyBoard && left.y + left.altura < canvas.height)
left.y += left.speed;
if(38 in keyBoard && right.y >0)
right.y -= right.speed;
if(40 in keyBoard && right.y + right.altura < canvas.height)
right.y += right.speed;
};
答案 0 :(得分:0)
您需要使用TouchEvents处理触控。您必须再添加3个与touchstart
,touchmove
和touchend
对应的事件监听器。触摸即可获得pageX和pageY。您必须将这些转换为相对于画布的位置,并应用您的逻辑来向上或向下移动条。
document.addEventListener("touchstart", handleTouchStart, false);
document.addEventListener("touchend", handleTouchMove, false);
document.addEventListener("touchend", handleTouchEnd, false);
var touchPosition = {
x: 0,
y: 0
};
function handleTouchStart(e) {
e.preventDefault();
touchPosition.x = e.changedTouches[0].pageX;
touchPosition.y = e.changedTouches[0].pageY;
var canvasPosition = canvas.getBoundingClientRect();
if (touchPosition.x - canvasPosition.left > canvas.width/2) {
// Trigger Right Bar
if (touchPosition.y - canvasPosition.top > right.y) {
// Move Down the Right Bar
}
else {
// Move Up the Right Bar
}
}
else {
// Trigger Left Bar and apply same logic as above
if (touchPosition.y - canvasPosition.top > right.y) {
// Move Down the left bar
}
else {
// Move Up the left bar
}
}
}
function handleTouchMove(e) {
// Handle When User drags along the touch point
}
function handleTouchEnd(e) {
// Handle Touch End
}