2017-09-24 30 views
0
矩形不會離開畫布

所以我創建使用JavaScript。這部影片在畫布上的一個矩形: https://www.youtube.com/watch?v=8ZPlNOzLrdw如何讓使用Javascript

window.onload = function() 
    { 

     var canvas = document.getElementById("c"); 

     canvas.addEventListener('keydown', moveIt, true); 

     ctx = canvas.getContext("2d"); 

     ctx.fillRect(100, 100, 30, 30); 

     var x = 100; 
     var y = 100; 


     function moveIt(e) 
    { 

     if (e.keyCode == 38) 
     { 
      ctx.clearRect(0, 0, canvas.width, canvas.height); 
      y = y - 10; 
      ctx.fillRect(x, y, 30, 30); 
     } 

     if (e.keyCode == 40) 
     { 
     ctx.clearRect(0, 0, canvas.width, canvas.height); 
     y = y + 10; 
     ctx.fillRect(x, y, 30, 30); 
     } 

     if (e.keyCode == 37) 
     { 
     ctx.clearRect(0, 0, canvas.width, canvas.height); 
     x = x - 10; 
     ctx.fillRect(x, y, 30, 30); 
     } 

     if (e.keyCode == 39) 
     { 
     ctx.clearRect(0, 0, canvas.width, canvas.height); 
     x = x + 10; 
     ctx.fillRect(x, y, 30, 30); 
     } 
    } 
} 

然而,當我按下鍵周圍,當它移動矩形到達不停止的邊緣。如何創建一個函數等,使其保持在畫布中,並在到達邊緣時停下來?

感謝您的幫助!

+0

_我的代碼看起來完全相同._ - **什麼**代碼?請[編輯]您的問題以提供上述代碼。 –

+0

我已經添加了代碼,我的意思是它在YouTube視頻中。 –

回答

0

您只需要額外的if語句即可在移動前進行檢查。在移動廣場之前,您需要確保y > 0y < canvas.height - 30(30爲您的廣場的高度)在移動之前,以及x與寬度相同。下面的代碼應該適合你:

function moveIt(e) { 

    if (e.keyCode == 38){ 
     if(y > 0){ 
      ctx.clearRect(0, 0, canvas.width, canvas.height); 
      y = y - 10; 
      ctx.fillRect(x, y, 30, 30); 
     } 
    } 

    if (e.keyCode == 40){ 
     if(y < canvas.height - 30){ 
      ctx.clearRect(0, 0, canvas.width, canvas.height); 
      y = y + 10; 
      ctx.fillRect(x, y, 30, 30); 
     } 
    } 

    if (e.keyCode == 37){ 
     if(x > 0){ 
      ctx.clearRect(0, 0, canvas.width, canvas.height); 
      x = x - 10; 
      ctx.fillRect(x, y, 30, 30); 
     } 
    } 

    if (e.keyCode == 39){ 
     if(x < canvas.width - 30){ 
      ctx.clearRect(0, 0, canvas.width, canvas.height); 
      x = x + 10; 
      ctx.fillRect(x, y, 30, 30); 
     } 
    } 
}