使用 setTimeout() 循环,使矩形变大,直到它到达画布边缘,然后重置

Using setTimeout() to loop, making a rectangle bigger until it hits the canvas edge and then resetting

本文关键字:布边缘 然后 边缘 循环 setTimeout 使用      更新时间:2023-09-26

我在使用 javascript setTimeout() 函数时遇到了一些问题。基本上,我想增加矩形的大小,直到它达到画布的最大高度或宽度,然后将其宽度和高度重置为 0 并保持循环。

可能我遇到的主要问题是在 if else 语句中,else 似乎从未以某种方式被调用,这对我来说毫无意义。我尝试将 else 更改为 if 表示高度/宽度是否等于或高于画布高度/宽度以将高度/宽度设置为 0,但这也不起作用。

这是我的代码:

<!DOCTYPE HTML>
<html>
    <head>
        <title>A Canvas</title>
        <style>
            canvas{border:20px solid black;}
        </style>
        <script>
            function drawMe()
            {
                var canvas2=document.getElementById("canvas1");
                var ctx = canvas2.getContext("2d");             
                width = 0;
                height = 0;
                draw(ctx, width, height);
            }
            function draw(ctx, width, height)
            {
                ctx.beginPath();
                ctx.fillStyle="#839402";
                ctx.fillRect(0,0,width,height);
                if (width < 900 && height < 500)
                {
                    width += 9;
                    height += 5;
                }
                else
                {
                    width = 0;
                    height = 0;
                }
                setTimeout(function() {draw(ctx, width, height)}, 20);
            }
        </script>
    </head>
    <body onload="drawMe();">
        <canvas id="canvas1" width="900" height="500">
            <!-- Stuff goes here -->
        </canvas>
    </body>
</html>

额外信息:

矩形正在正常增长,在矩形碰到画布边缘之前,一切看起来都很好。此时,矩形只是停止增长,不会发生任何其他情况。它应该将矩形的高度和宽度重置为 0,并在无限循环中重新开始整个过程,但由于某种原因没有。

您必须记住,每次drawMe调用之间都不会清除画布 - 因此,虽然宽度和高度已正确调整,但在第一次循环之后,整个区域被绘制过来,因此看起来什么都没有发生。

添加简单的透明填充可以解决此问题。

小提琴here ! http://jsfiddle.net/YAJnk/