2017-09-24 31 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); 
     } 
    } 
}