2017-04-18 101 views
1

我正在尝试在JavaScript中使用箭头键在画布上移动对象(圆/球)的简单游戏。我花了很多时间进行研究和编码,但目前为止没有运气,所以我希望你们能帮助我。现在,我只是试着用箭头键[向上,向下,向左,向右]移动物体/球。任何人都能弄清楚,为什么这不起作用?非常感谢你提前。在JavaScript中使对象在画布上移动

var canvas = document.getElementById("mycanvas"); 
 
var ctx = canvas.getContext("2d"); 
 

 
canvas.width = canvas.height = 500; 
 

 
//the circle 
 
function circle() { 
 
    ctx.beginPath(); 
 
    ctx.arc(50, 50, 25, 0, Math.PI * 2, true); 
 
    ctx.fillStyle = "blue"; 
 
    ctx.fill(); 
 
} 
 

 
circle(); 
 

 
//move function for going left 
 
window.addEventListener("keydown", function(event) { 
 
    if (event.keyCode == 37) { 
 
     circle.x = 1; 
 
    } 
 
})

+0

所以移动圆圈......答案在于这一行('ctx.arc(50,50,25,0,Math.PI * 2,true);') – evolutionxbox

回答

2

你可以完成下列方式这样的运动......

var canvas = document.getElementById("mycanvas"); 
 
var ctx = canvas.getContext("2d"); 
 
var x = 50, 
 
    y = 50, 
 
    radius = 15, 
 
    speed = 3; 
 

 
function circle() { 
 
    ctx.beginPath(); 
 
    ctx.arc(x, y, radius, 0, Math.PI * 2, true); 
 
    ctx.fillStyle = "#07C"; 
 
    ctx.fill(); 
 
} 
 

 
function draw() { 
 
    ctx.clearRect(0, 0, canvas.width, canvas.height); 
 
    circle(); 
 
    requestAnimationFrame(draw); 
 
} 
 

 
draw(); 
 

 
window.addEventListener("keydown", function(e) { 
 
    switch (e.key) { 
 
     case 'ArrowUp': 
 
      if (y > radius) y -= speed; 
 
      break; 
 
     case 'ArrowDown': 
 
      if (y < canvas.height - radius) y += speed; 
 
      break; 
 
     case 'ArrowLeft': 
 
      if (x > radius) x -= speed; 
 
      break; 
 
     case 'ArrowRight': 
 
      if (x < canvas.width - radius) x += speed; 
 
      break; 
 
    } 
 
});
canvas { 
 
    border: 1px solid black; 
 
}
<canvas id="mycanvas" width="200" height="200"></canvas>

道歉不作任何解释

+0

它确实如此。我不确定我是否完全理解您的解决方案(对于编码/编程非常新颖),但会确保彻底研究它。非常感谢您的宝贵时间。 – thesystem

+0

@thesystem最受欢迎:) –

+0

@thesystem也请考虑接受答案,如果这有助于你以任何方式:) –