【发布时间】:2021-06-15 08:03:29
【问题描述】:
在这段代码中,我一直在尝试使用键盘上的箭头键移动一个矩形。我已经根据this tutorial编写了条件,但是我的项目略有不同所以我更改了代码但问题仍然存在的对象。
我有 2 个事件侦听器用于按键被按下和未按下,并且我使用了一些标志变量来查看按钮的状态并根据它移动对象。
对不起,如果我的问题很愚蠢,我是这个编程领域的新手,我已经花了几个小时来解决这个问题。
<script>
//canvas
var canvas = document.getElementById("gameScreen");
var ctx = canvas.getContext("2d");
const width = 1000;
const height = 700;
//user controllers
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
//keydown handler
document.addEventListener("keydown",(e)=>{
if(e.key == "Up" || e.key == "ArrowUp"){
upPressed = true;
}
else if(e.key == "Down" || e.key == "ArrowDown"){
downPressed = true;
}
else if(e.key == "Right" || e.key == "ArrowRIght"){
rightPressed = true;
}
else if(e.key == "Left" || e.key == "ArrowLeft"){
leftPressed = true;
}
}, false);
//keyup handler
document.addEventListener("keyup",(e)=>{
if(e.key == "Up" || e.key == "ArrowUp"){
upPressed = false;
}
else if(e.key == "Down" || e.key == "ArrowDown"){
downPressed = false;
}
else if(e.key == "Right" || e.key == "ArrowRIght"){
rightPressed = false;
}
else if(e.key == "Left" || e.key == "ArrowLeft"){
leftPressed = false;
}
}, false);
// Player Object
let Player = function(x,y){
this.x = x;
this.y = y;
this.width = 50;
this.height = 50;
this.getDirection = function(){
if(downPressed){
this.y -= 10;
}else if(upPressed){
this.y += 10;
}else if(rightPressed){
this.x += 10;
}else if(leftPressed){
this.x -= 10;
}
}
this.update = function(){
this.getDirection();
this.draw();
};
this.draw = function(){
ctx.clearRect(0,0,width,height);
ctx.fillRect(this.x,this.y,this.width,this.height);
ctx.fill();
};
}
let player = new Player(200,200)
let callback = player.update();
requestAnimationFrame(callback)
</script>
【问题讨论】:
-
也许您的问题是您将
player.update的返回值作为回调传递,因为您正在调用该函数,它应该是let callback = player.update;。此外,您可能需要将requestAnimationFrame(callback);放入setInterval()以使其连续运行。 -
@ArkinSolomon 我刚刚检查过,但也不是这样。
-
代码不完整。
callback在哪里?我还将添加 canvas HTML 并使其成为一个可运行的 sn-p,它可以清楚地重现问题并使其更容易提供帮助。 -
@ggorlen 回调只是 requestAnimationFrame 函数上方的一行。
标签: javascript html web canvas html5-canvas