猿问

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

我想将游戏从 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/


慕田峪7331174
浏览 117回答 1
1回答

ITMISS

而不是onload="startGame()". 将keypress事件添加到您的文档并检查它的keyCode空间 i:e 32。document.body.addEventListener('keypress', function(e) {&nbsp; &nbsp; if(e.keyCode == 32) {&nbsp; &nbsp; &nbsp; &nbsp; startGame();&nbsp; &nbsp; }});document.body.addEventListener('keypress', function(e) {&nbsp; &nbsp; if(e.keyCode == 32) {&nbsp; &nbsp; &nbsp; console.log('spacebar');&nbsp; &nbsp; }});<p> Press spacebar </p>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答