JavaScript无法填充画布

问题描述 投票:-1回答:1

正义开始编写此程序,这是使用JavaScript绘制图像的新手。如果我取消了var = turret的声明,则将绘制背景,但是一旦声明turret,它将无法绘制背景。有什么想法吗?

谢谢,

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>JavaShooter</title>
    <style></style>
</head>

<body>
    <canvas id="gameCanvas" width="700" height="500"></canvas>
    <script>
        const FPS = 30; //frames per second rate
        const turretSize = 30; //turret height in px

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

        var turret = {
            x: canv.width / 2;
            y: canv.height / 2;
            r: turretSize / 2;
            a: 90 / 180 * Math.PI; //converted to radians
        }

        //game loop
        setInterval(update, 1000/FPS);

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

            //draw triangular turret
            ctx.strokeStyle = "yellow";
            stroke.lineWidth = 1;

            ctx.beginPath();
            ctx.moveTo(   //tip of turret
                turret.x + turret.r * Math.cos(turret.a), 
                turret.y - turret.r * Math.sin(turret.a)  
                      );
            ctx.lineTo(   //rear left of turret
                turret.x - ship.r * Math.cos(turret.a) + Math.sin(turret.a),
                turret.y + ship.r * Math.cos(turret.a) - Math.sin(turret.a)
            )
            ctx.stroke();
        }
javascript html canvas draw fill
1个回答
0
投票

[第一件事是制作转塔时,您正在使用分号。试试:

var turret = {
    x: canv.width / 2, // try commas instead
    y: canv.height / 2,
    r: turretSize / 2,
    a: 90 / 180 * Math.PI //converted to radians
}

还有其他一些错误,例如stroke.lineWidth,未定义笔划和ship.r,未定义船。希望这将有助于您正确定义转塔。

© www.soinside.com 2019 - 2024. All rights reserved.