线条未在画布中绘制

时间:2018-06-23 13:15:20

标签: javascript html canvas

<!DOCTYPE html>
<html lang="en" dir="ltr">

    <head>
        <meta charset="utf-8">
        <title>Asteroids</title>
        <style media="screen">
        </style>
    </head>

    <body>
        <canvas id="gameCanvas" width="700" height="500"></canvas>
        <script type="text/javascript">
            const FPS = 30; // frames per second
            const SHIP_SIZE = 30; // ship height in pixels

            /* @type {HTMLCanvasElement} */
            var canv = document.getElementById('gameCanvas');
            var ctx = canv.getContext("2d");

            var ship = {
                x: canv.width / 2,
                y: canv.height / 2,
                r: SHIP_SIZE / 2,
                a: 90 / 180 * Math.pi // Convert to radians
            }

            // set up the game loop
            setInterval(update, 1000 / FPS);

            function update() {
                // draw space
                ctx.fillStyle = "black";
                ctx.fillRect(0, 0, canv.width, canv.height);

                // draw triangular ship
                ctx.strokeStyle = "white";
                ctx.lineWidth = SHIP_SIZE / 20;
                ctx.beginPath();
                ctx.moveTo( // nose of the ship
                    ship.x + 4 / 3 * ship.r * Math.cos(ship.a),
                    ship.y - 4 / 3 * ship.r * Math.sin(ship.a)
                );
                ctx.lineTo( // rear left
                    ship.x - ship.r * (2 / 3 * Math.cos(ship.a) + Math.sin(ship.a)),
                    ship.y + ship.r * (2 / 3 * Math.sin(ship.a) - Math.cos(ship.a))
                );
                ctx.lineTo( // rear right
                    ship.x - ship.r * (2 / 3 * Math.cos(ship.a) - Math.sin(ship.a)),
                    ship.y + ship.r * (2 / 3 * Math.sin(ship.a) + Math.cos(ship.a))
                );
                ctx.closePath();
                ctx.stroke();

                // rotate ship

                // move the ship

                // center dot
                ctx.fillStyle = "red";
                ctx.fillRect(ship.x - 1, ship.y - 1, 2, 2);
            }
        </script>
    </body>
</html>

我不知道为什么这段代码没有画线。每当我在moveTo函数之后绘制一条线时,都不会绘制它,但是指针会转到指定的位置。当我再次使用lineTo函数绘制线条时,仅当未在其中使用JavaScript Math函数或在先前的moveTo或lineTo函数中未使用javascript Math函数时才绘制该线条。我不明白发生了什么。谁能帮我吗?

1 个答案:

答案 0 :(得分:1)

不是不是 Math.pi,它是 Math.PI

使用Math.pi会导致NaN,因此未画线。

只需将其更改为

a: 90 / 180 * Math.PI // Convert to radians