首页 > 解决方案 > 画布上没有画线

问题描述

<!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 函数中使用时才会绘制它。我无法理解发生了什么。谁能帮帮我吗?

标签: javascripthtmlcanvas

解决方案


不是Math.piMath.PI

使用未绘制线的Math.pi结果。NaN

只需将其更改为

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


推荐阅读