gpt4 book ai didi

javascript - 嘿!我如何解决我的代码显然没有从浏览器的 KeyboardEvent 正确获取 .key 属性?

转载 作者:行者123 更新时间:2023-11-30 09:17:48 25 4
gpt4 key购买 nike

KeyboardEvent 的“预定义”值 = .key 取决于您在键盘上按下的键,但即使我的控制台显示我单击了某个键,我也无法“定义”键值....

我尝试使用谷歌搜索解决方案并自行定义关键值,但没有任何效果我现在有点无能

  let canvas= document.querySelector('canvas');
canvas.width=800;canvas.height=600;const ctx=canvas.getContext('2d');
//bg
ctx.fillStyle='black';
ctx.fillRect(0,0,canvas.width,canvas.height);
//player
ctx.fillStyle='white';
let player_x=30;
let player_y=60;
ctx.fillRect(player_x,player_y,40,400);
//controls
function Input(event){
let ifPressed=event.key;
console.log(ifPressed);
if(ifPressed==="w"){
player_y-=5;
} else if(ifPressed==="s"){
player_y+=5;
}

}

document.addEventListener('keydown',Input);
Input();

我已经尝试过这种方式,但控制台总是说“.key”未定义,而它应该从浏览器中的 KeyboardEvent 获取键属性

最佳答案

删除 Input();在最后一行创建 <canvas></canvas>元素在你的正文 html 中。我将这两个修复程序添加到您的代码中并且它有效(运行代码段,向下滚动,单击 Canvas 并开始键入):

let canvas= document.querySelector('canvas');
canvas.width=800;canvas.height=600;const ctx=canvas.getContext('2d');
//bg
ctx.fillStyle='black';
ctx.fillRect(0,0,canvas.width,canvas.height);
//player
ctx.fillStyle='white';
let player_x=30;
let player_y=60;
ctx.fillRect(player_x,player_y,40,400);
//controls
function Input(event){
let ifPressed=event.key;
console.log(ifPressed);
if(ifPressed==="w"){
player_y-=5;
} else if(ifPressed==="s"){
player_y+=5;
}

}


document.addEventListener('keydown',Input);
<canvas></canvas>

关于javascript - 嘿!我如何解决我的代码显然没有从浏览器的 KeyboardEvent 正确获取 .key 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53873027/

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