如何根据我的代码清除 JavaScript 中的旧矩形迭代

How to clear old rectangle iterations in JavaScript based on my code

我试图查看此处的其他答案,但我的代码不同,所以我不知道何时使用 clearRect();清除旧的矩形并让我的代码产生方块在我的屏幕上移动的错觉。

为了给读者一个视觉效果,我正在尝试创建我的第一个塔防游戏,所以我希望所有的敌人(方块)在一条线上移动但有一点间距。

<!DOCTYPE html>
<html>
<head>
<title>Tower Defense</title>
</head>
<body>

<canvas id="canvas" height="600" width="600" style="background: url('pictures/map.png'); background-position:center; background-size:cover"></canvas>

<script type="text/javascript">

    let ctx = document.getElementById('canvas').getContext('2d');

    let enemies = [];

    window.onload = function() {
        setInterval(showEnemies, 60);
    }


    //this function shows all enemies that spawn;
    function showEnemies() {
        let x = 0;
        for (let i = 0; i < 10; i++) {
            let mainEnemy = new Enemy(x+=25, 75, 20, "blue");
            enemies.push(mainEnemy);
        }
        for (let i = 0; i < enemies.length; i++) {
            enemies[i].showEnemy();

            enemies[i].moveEnemy();
        }



    }

    function Enemy(x, y, size, color) {
        this.x = x;
        this.y = y;
        this.size = size;
        this.speedX = 1;
        this.speedY = 1;

        this.showEnemy = function() {

            ctx.fillStyle = color;
            ctx.fillRect(this.x, this.y, this.size, this.size);
        }

        this.moveEnemy = function() {
            this.x+=this.speedX;

        }
    }

</script>

如果有人能给我一个关于在哪里放置 clearRect() 的解释,我将不胜感激。

在绘制正方形之前,您需要清除 canvas 每一帧

ctx.clearRect(0, 0, 600, 600); 
for (let i = 0; i < enemies.length; i++) {
    enemies[i].showEnemy();
    enemies[i].moveEnemy();
}

我还建议将这部分代码移到 showEnemies() 函数之外

for (let i = 0; i < 10; i++) {
        let mainEnemy = new Enemy(x+=25, 75, 20, "blue");
        enemies.push(mainEnemy);
    }