【发布时间】:2020-08-15 08:03:07
【问题描述】:
我正在制作一个青蛙复制品,我希望青蛙在我按下一个键时只移动一次,基本上是为了防止它在按住一个键时移动多次。
这是我的代码中处理keydown 事件的相关部分:
document.onkeydown = function(e) {
var key = e.which || e.keyCode;
if (key == 37){ frog.x = frog.x - 50; }
if (key == 38){ frog.y = frog.y - 50; }
if (key == 39){ frog.x = frog.x + 50; }
if (key == 40){ frog.y = frog.y + 50; }
};
更新:
我让它在按住键时不移动,但现在它不会让我在我向右移动一次后立即移动,但如果我单击另一个按钮会重置,然后再次执行相同的操作:
const canvas = document.getElementById('canvas');
const c = canvas.getContext('2d');
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
let frog = {
x: 0,
y: 0,
fw: 50,
fh: 50,
fmx: 0,
fmy: 0,
};
let counter = 0;
function animate() {
requestAnimationFrame(animate);
// Clear previous scene:
c.clearRect(0, 0, window.innerWidth, window.innerHeight);
// Draw frog:
c.fillStyle = '#000'
c.fillRect(frog.x, frog.y, frog.fw, frog.fh);
// Movement of the frog with keys:
document.onkeydown = function(e) {
e = e || window.event;
var key = e.which || e.keyCode;
if (key == 65 && counter === 0) { frog.x = frog.x - 50, counter = 1 }
if (key == 87 && counter === 0) { frog.y = frog.y - 50, counter = 1 }
if (key == 68 && counter === 0) { frog.x = frog.x + 50, counter = 1 }
if (key == 83 && counter === 0) { frog.y = frog.y + 50, counter = 1 }
};
document.onkeyup = function(e) {
e = e || window.event;
var key = e.which || e.keyCode;
if (key == 65) { counter = 0 }
if (key == 87) { counter = 0 }
if (key == 68) { coutner = 0 }
if (key == 83) { counter = 0 }
};
}
animate();
body {
margin: 0;
}
#canvas {
width: 100%;
height: 100%;
}
<canvas id="canvas" />
【问题讨论】:
标签: javascript event-handling html5-canvas dom-events keyboard-events