2016-12-18 28 views
0

我如何放入我的funtion 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; 
    }; 

https://jsfiddle.net/bd7v016e/1/

+0

我試過你在jsfiddle上的應用程序。 看來,一切都好了 我把速度設置爲5,這對我更好。 我沒有看到任何問題。 你能詳細說明你的問題嗎? – Roge

回答

0

你需要使用TouchEvents處理觸摸。您必須再添加3個對應於touchstarttouchmovetouchend的事件偵聽器。觸摸你可以得到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 
} 
相關問題