移动球的游戏无法使用javascript

时间:2016-10-26 16:23:40

标签: javascript html html5 canvas

我使用javascript和sublime创建了这个游戏。理论上我应该想象两个球在画布周围移动,但实际上我看到只有一个黄色的球停在画布的中间。为什么球不动?

这是代码:

<!DOCTYPE html>
<html>
<head>
    <title>Canvas Tutorial</title>
    <script type="text/javascript">
        window.onload = draw;

        function draw() {


            var canvas = document.getElementById("canvas");
            var ctx = canvas.getContext("2d");

            ctx.fillStyle = "black";
            ctx.fillRect(0, 0, 400, 300);
            ctx.fillStyle = "yellow";
            ctx.beginPath();

            for (var i = 0; i < circles.length; i++) {
                ctx.arc(circles[i].x, circles[i].y, circles[i].r, 0, Math.PI * 2, false);
                ctx.fill();

                if ((circles[i].y > 300 - circles[i].r) && circles[i].direction === 1) {
                    circles[i].direction = 2;
                } else if ((circles[i].x > 400 - circles[i].r) && (circles[i].direction === 2)) {
                    circles[i].direction = 3;
                } else if ((circles[i].y > 300 - circles[i].r) && (circles[i].direction === 4)) {
                    circles[i].direction = 3;
                } else if ((circles[i].y <= circles[i].r) && circles[i].direction === 3) {
                    circles[i].direction = 4;
                } else if ((circles[i].x < circles[i].r) && circles[i].direction === 4) {
                    circles[i].direction = 1;
                } else if ((circles[i].y < circles[i].r) && circles[i].direction === 2) {
                    circles[i].direction = 1;
                }

                if (circles[i].direction === 1) {

                    circles[i].x += circles[i].speedX;
                    circles[i].y += circles[i].speedY;
                } else if (circles[i].direction === 2) {

                    circles[i].x += circles[i].speedX;
                    circles[i].y -= circles[i].speedY;
                } else if (circles[i].direction === 3) {

                    circles[i].x -= circles[i].speedX;
                    circles[i].y -= circles[i].speedY;
                } else {

                    circles[i].x -= circles[i].speedX;
                    circles[i].y += circles[i].speedY;
                }
            }
        }

        var circles = [{ x: 200, y: 150, r: 40, direction: 1, speedX: 1, speedY: 2 }, { x: 200, y: 150, r: 70, direction: 1, speedX: 2, speedY: 1 }];

        setTimeout(draw, 10);



    </script>
</head>
<body>
    <canvas id="canvas" width="400" height="300"></canvas>

</body>
</html>

4 个答案:

答案 0 :(得分:1)

不确定上面的2个答案是什么,他确实定义了圈子。问题似乎是使用setInterval而不是setTimeout。

答案 1 :(得分:0)

您应该在循环之前定义圆圈。 :)

答案 2 :(得分:0)

您没有定义圈子

for (var i = 0; i < circles.length; i++) {}

没有圆圈,所以没有循环。

答案 3 :(得分:0)

试试这个: -

 <canvas id="game" width="512" height="256"></canvas>

链路: - http://blog.mailson.org/2013/02/simple-pong-game-using-html5-and-canvas/