JavaScript,无法绘制乒乓球中的 Racket 和球。有人可以解释一下为什么吗?

标签 javascript canvas pong

有人可以解释一下为什么这段代码不起作用吗?到目前为止,它应该在 Canvas 上绘制两个桨和一个球(矩形)。我是 JavaScript 新手,我正在关注这个 YouTube 教程,但我几乎从一开始就陷入了困境。除了不知道为什么它没有绘制游戏的所有元素之外,我也不明白 main 函数内 var = Loop 函数的含义。请帮忙!!

    var WIDTH=700;
    var HEIGHT=500;
    var pi=Math.PI;

    var canvas;
    var ctx;
    var keystate;

    var player;
    var ai;
    var ball;

    player = {
        x: null,
        y: null,
        width: 20,
        height: 100,

        update: function(){},
        draw: function (){
            ctx.fillRect(this.x, this.y, this.width, this.height);
            }
    }

    ai = {
        x: null,
        y: null,
        width: 20,
        height: 100,

        update: function(){},
        draw: function (){
            ctx.fillRect(this.x, this.y, this.width, this.height);
            }
    }


    ball = {
        x: null,
        y: null,
        side: 20,

        update: function(){},
        draw: function (){
            ctx.fillRect(this.x, this.y, this.side, this.side);
            }
    }


    function main(){
        canvas = document.createElement("canvas");
        canvas.width = WIDTH;
        canvas.height = HEIGHT;
        ctx = canvas.getContext("2d");
        document.body.appendChild(canvas);

        init();

        var loop = function(){
            update();
            draw();

            window.requestAnimationFrame(loop,canvas);
        };
        window.requestAnimationFrame(loop,canvas);
    }

    function init(){
        player.x = player.width;
        player.y = (HEIGHT - player.height)/2;

        ai.x = WIDTH - (player.width + ai.width);
        ai.y = (HEIGHT - ai.height)/2;

        ball.x = (HEIGHT - ball.side)/2;
        ball.y = (HEIGHT - ball.side)/2;
    }

    function update(){
        ball.update();
        player.update();
        ai.update();
    }

    function draw(){
        ctx.fillRect(0,0,WIDTH,HEIGHT);
        ctx.fillStyle = "#fff";

        ball.draw();
        player.draw();
        ai.draw();
    }

    main();

</script>

最佳答案

你把所有东西都画成了白色。 这就是为什么你什么也看不见的原因。背景是白色的,您绘制的形状也是白色的。

尝试

function draw(){
    ctx.fillStyle = "#fff";
    ctx.fillRect(0,0,WIDTH,HEIGHT);

    ctx.save();
    ctx.fillStyle = "#000"
    ball.draw();
    player.draw();
    ai.draw();
    ctx.restore();
}

关于JavaScript,无法绘制乒乓球中的 Racket 和球。有人可以解释一下为什么吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23306968/

相关文章:

javascript - 即忽略一般的 javascript 文件或代码

javascript - Fabricjs 选择鼠标单击多个对象

javascript - 无法读取未定义的属性 'canvas'

javascript - 在 WebGL 与 WebGL 中模拟基于调色板的图形 Canvas 二维

python - 如何让多个键绑定(bind)在 turtle 图形中同时工作?

c# - XNA 模型球体不会与四个壁面网格中的一个或全部发生碰撞

javascript - AngularJS 将字符串作为函数传递给 ng-click

javascript - AngularJS 轮播不工作

javascript - 根据 Material UI 中的用户输入使 TextField 错误为 true

c++ - 管理 SDL 中的输入?