为了账号安全,请及时绑定邮箱和手机立即绑定

如何将程序从 onload 开始更改为从 Space press 开始?

如何将程序从 onload 开始更改为从 Space press 开始?

慕田峪7331174 2021-06-15 17:52:08
我想将游戏从 onload 更改为 onkeydown(空格),但我不知道如何将整个代码置于 onkeydown 命令下。我是编程爱好者,这是我的第一个项目之一,所以感谢您的帮助:)<body onload="startGame()"><script>function startGame() {myGameArea.start();}var myGameArea = {canvas : document.createElement("canvas"),start : function() {    this.canvas.width = 220;    this.canvas.height = 400;    this.context = this.canvas.getContext("2d");    document.body.insertBefore(this.canvas, document.body.childNodes[0]);this.frameNo = 0;updateGameArea();    },clear : function() {    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);} }function component(width, height, color, x, y, type) {this.type = type;function everyinterval(n) {    if ((myGameArea.frameNo / n) % 1 == 0) {return true;}    return false;}function accelerate(n) {    if (!myGameArea.interval) {myGameArea.interval = setInterval(updateGameArea, 20);}    myGamePiece.gravity = n;}function reload(){    window.location.reload(true);}document.onkeydown = function(event){    if(event.keyCode === 27)        paused = !paused;}</script><button onmousedown="accelerate(-0.2); myMusic.play();" onmouseup="accelerate(0.05)">szybuj :')</button>jsFiddle:https ://jsfiddle.net/sidka/k1f4ow0q/6/
查看完整描述

1 回答

?
ITMISS

TA贡献1871条经验 获得超8个赞

而不是onload="startGame()". 将keypress事件添加到您的文档并检查它的keyCode空间 i:e 32。


document.body.addEventListener('keypress', function(e) {

    if(e.keyCode == 32) {

        startGame();

    }

});

document.body.addEventListener('keypress', function(e) {

    if(e.keyCode == 32) {

      console.log('spacebar');

    }

});

<p> Press spacebar </p>


查看完整回答
反对 回复 2021-06-24
  • 1 回答
  • 0 关注
  • 116 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信