Alex Podworny
Alex Podworny

Reputation: 1019

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

I'm having some issues playing with the javascript setTimeout() function. Basically I want to increase the size of a rectangle until it hits either the maximum height or width of the canvas, and then reset its width and height to 0 and keep the loop going.

Possibly the main issue I'm having is in the if else statement, the else seems to somehow never gets called, which makes no sense to me. I've tried changing the else to an if saying if the height/width is at or over the canvas height/width to set the height/width to 0, but that didn't work either.

Here is the code I have:

<!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>

Extra info:

The rectangle is growing properly and everything looks completely fine up until the rectangle hits the edges of the canvas. At that point, the rectangle just simply stops growing and nothing else happens. It should reset the height and width of the rectangle to 0 and restart the whole process over again in an infinite loop, but it doesn't for some reason.

Upvotes: 0

Views: 1023

Answers (1)

eithed
eithed

Reputation: 4320

You have to remember that your canvas isn't cleared between each of your drawMe calls - so, while the width and height are properly adjusted, after the first loop the whole area is drawn over and thus it appears nothing is happening.

Adding a simple clear fill solves the issue.

A fiddle here! http://jsfiddle.net/YAJnk/

Upvotes: 1

Related Questions