首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScript,不会在乒乓球上画球拍。有人能给我解释一下为什么吗?

JavaScript,不会在乒乓球上画球拍。有人能给我解释一下为什么吗?
EN

Stack Overflow用户
提问于 2014-04-26 13:20:56
回答 1查看 214关注 0票数 0

有人能给我解释一下为什么这个代码不能工作吗?到目前为止,它应该在画布上绘制两个球拍和一个球(矩形)。我是JavaScript的新手,我正在学习这篇YouTube教程,但我几乎一开始就卡住了。除了不知道为什么它没有绘制游戏的所有元素之外,我也不理解main函数中var = loop函数的含义。请帮帮我!

代码语言:javascript
复制
    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>
EN

回答 1

Stack Overflow用户

发布于 2014-04-26 13:44:00

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

试一试

代码语言:javascript
复制
function draw(){
    ctx.fillStyle = "#fff";
    ctx.fillRect(0,0,WIDTH,HEIGHT);

    ctx.save();
    ctx.fillStyle = "#000"
    ball.draw();
    player.draw();
    ai.draw();
    ctx.restore();
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23306968

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档