You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在太空侵略者游戏中按空格射击时阻止页面滚动?

问题描述

我正在制作一款简易的Space Invaders(太空侵略者)游戏,使用空格键发射子弹。问题在于,按下空格时,除了发射子弹,由于我使用了尺寸较大的canvas,页面还会向下滚动。是否有办法在保留页面滚动功能的前提下阻止这种情况?我是编程新手,若问题过于基础还请见谅。

我曾尝试在CSS文件中添加以下代码:

body {
   overflow: 'hidden";
}

但这并不奏效,因为它会完全隐藏屏幕外的所有内容,而不仅仅是禁用空格键触发的滚动。


现有代码

CSS 文件

body{
    font-family:'Courier New', Courier, monospace;
    text-align: center;
}
#board {
    border-bottom: 1px solid black;
}

HTML 文件

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport", content="width=device-width, initial-scale=1.0">
        <title>Space Invaders</title>
        <link rel="stylesheet" href="spaceinvaders.css">
        <script src="spaceinvaders.js"></script>
    </head>
    <body>
        <h1>Space Invaders</h1>
        <canvas id="board"></canvas>
        <p>blahblahblahbalhablahjgbksvdbsugbsdgudgudsughusdhdguihsduihg</p>
    </body>
</html>

JavaScript 文件

//board
let board;
let boardWidth = 500;
let boardHeight = 600;
let context;

let gameOver = false

//ship
let shipWidth = 75;
let shipHeight = 95;
let shipX = 218;
let shipY = 500;
let shipImg; 
//actual dimentions
//21px from left edge
//24px from right edge
//middle at 45 from left edge
//middle 51 from right edge

//bullet
let bulletArray = [];
let bulletWidth = 75;
let bulletHeight = 95;
let bulletX = 218

//ship varuble
let ship = {
    x : shipX,
    y : shipY,
    width : shipWidth,
    height : shipHeight
}

//physics for ship

let Xspeed = 0;
let moveLeft = false;
let moveRight = false;

//physics for bullet
let bulletSpeed = 2
window.onload = function() { //when game starts 
    board = document.getElementById("board");
    board.height = boardHeight;
    board.width = boardWidth;

    context = board.getContext("2d"); //used for drawing on the board

    //draw initial dinosaur
    // context.fillStyle="green";
    // context.fillRect(dino.x, dino.y, dino.width, dino.height);

    shipImg = new Image();
    shipImg.src = "./spaceinvadersImgs/ship.png";
    shipImg.onload = function() {
        console.log("imgLoaded")
        context.drawImage(shipImg, ship.x, ship.y, ship.width, ship.height);
    }
    bulletImg = new Image();
    bulletImg.src = "./spaceinvadersImgs/bullet.png";

    
    window.addEventListener("keydown", function(e){
        switch(e.key){
            case "ArrowLeft":
                moveLeft = true
                break;
            case "ArrowRight":
                moveRight = true
                break;
            case " ":
                console.log("shoot bullet")
                if (e.key === " "){
            
                    //place bullet
                    let bullet = {
                        img : bulletImg,
                        x : ship.x,
                        y : 536,
                        width : bulletWidth,
                        height: bulletHeight
                    }
                        bulletArray.push(bullet); //add bullet at this moment to the array
            
                    if (bulletArray.length > 25) {
                        bulletArray.shift(); //remove the first element from the array so that the array doesn't constantly grow
                    }
                }

        }
    }, false);
    window.addEventListener("keyup", function(e){
        switch(e.key){
            case "ArrowLeft":
                moveLeft = false
                break;
            case "ArrowRight":
                moveRight = false
                break;
            
        }
    }, false);
    update()
}
function update(){
    requestAnimationFrame(update);
    console.log("update")
    //preping for next frame
    if (gameOver) {
        return;
    }

    if(ship.x < 0 && Xspeed == -5 || ship.x > 500 && Xspeed == 5){
        Xspeed = 0
    }
    ship.x += Xspeed;   

    if(moveLeft && !moveRight){
        Xspeed = -5
    }
    if(moveRight && !moveLeft){
        Xspeed = 5
    }
    if(!moveLeft && !moveRight){
        Xspeed = 0
    }
   

    context.clearRect(0, 0, board.width, board.height);

    for (let i = 0; i < bulletArray.length; i++) {
        let bullet = bulletArray[i];
        bullet.y -= bulletSpeed;
        context.drawImage(bullet.img, bullet.x, bullet.y, bullet.width, bullet.height);
    }
    context.drawImage(shipImg, ship.x, ship.y, ship.width, ship.height);
};

解决方案

问题根源是空格键的默认行为会触发页面滚动,只需在空格键的事件处理逻辑中添加e.preventDefault(),就能单独阻止这个默认行为,同时保留页面原本的滚动功能(比如鼠标滚轮、拖拽滚动条)。

修改JavaScript中keydown事件里的空格键处理部分:

case " ":
    e.preventDefault(); // 阻止空格键触发页面滚动的默认行为
    console.log("shoot bullet")
    if (e.key === " "){
        //place bullet
        let bullet = {
            img : bulletImg,
            x : ship.x,
            y : 536,
            width : bulletWidth,
            height: bulletHeight
        }
        bulletArray.push(bullet); //add bullet at this moment to the array

        if (bulletArray.length > 25) {
            bulletArray.shift(); //remove the first element from the array so that the array doesn't constantly grow
        }
    }

这样修改后,按下空格键只会执行发射子弹的逻辑,不会导致页面滚动,同时页面的正常滚动功能不受影响。

内容的提问来源于stack exchange,提问作者ilikegrape

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 01:48:14