AlbertVanNeinstein
AlbertVanNeinstein

Reputation: 3

Rectangles won't draw

This is supposed to draw 3 shapes to the screen (2 rectangles and a square). But whenever I run it, it just shows a blank screen in Google Chrome. There are no errors in the console, so there's nothing wrong with the code (that I can see). Any and all help is greatly appreciated! Thanks.

<!DOCTYPE html>
<html>

<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>

<body>

<script>
    var WIDTH=1920, HEIGHT=1080, pi=Math.PI;
    var canvas, ctx, keystate;
    var Player, AI, Ball;

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

        update: function() {},
        draw: function() {
            ctx.fillRect(this.x, this.y, this.height, this.width);
        }
    }
    AI = {
        x: null,
        y: null,
        width: 20,
        height: 100,

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

    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.x)/2;

        AI.x = WIDTH(Player.width + AI.width);
        AI.y = (HEIGHT - AI.x)/2;

        Ball.x = (WIDTH - 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.save();
        ctx.fillStyle = "#fff";

        Ball.draw();
        Player.draw();
        AI.draw();

        ctx.restore();
    }

    main()
</script>
</body>
</html>

Upvotes: 0

Views: 40

Answers (1)

Overv
Overv

Reputation: 8529

There are several errors in your code, which you could have found by opening the developer console in your browser:

AI.x = WIDTH(Player.width + AI.width);

Should be:

AI.x = WIDTH * (Player.width + AI.width);

Otherwise it will be treated as a function call. And:

player.x = player.width;
player.y = (HEIGHT - Player.x)/2;

Should be:

Player.x = Player.width;
Player.y = (HEIGHT - Player.x)/2;

JavaScript is case sensitive.

Upvotes: 1

Related Questions