gpt4 book ai didi

javascript - 如何检查动画循环中是否按下了空格键? (在 JavaScript 中)

转载 作者:行者123 更新时间:2023-12-01 03:30:38 25 4
gpt4 key购买 nike

我有我的动画循环:

function animate() {
//draw every thing
requestAnimationFrame(animate);
};
animate();

效果很好,但是按下空格键时如何更新它?

我希望有这样的事情:

function animate() {
if (spacebar_pressed) {
//draw something
} else {
//draw something else
};
requestAnimationFrame(animate);
};
animate();

我还应该提到,只有 JavaScript 答案才有用。

最佳答案

使用设置为 false 的 bool 变量 spacebar_pressed。当有 keydown 事件且按键代码为 32(空格键)时,将其设置为 true。当存在键代码为 32 的 keyup 事件时,将其设置为 false

var spacebar_pressed = false;

window.onkeydown = function(event) {
if (event.keyCode == 32) {
spacebar_pressed = true;
};
};
window.onkeyup = function() {
if (event.keyCode == 32) {
spacebar_pressed = false;
};
}

function animate() {
if (spacebar_pressed) {
//draw something
} else {
//draw something else
};
requestAnimationFrame(animate);
};

animate();

需要注意的是,Firefox 不支持 event.keycode,而是使用 event.which

感谢 @Traktor53你的答案!

关于javascript - 如何检查动画循环中是否按下了空格键? (在 JavaScript 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44558140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com