0

I'm currently trying to create a canvas with raindrops falling, and my only problem is that the drops aren't clearing after they spawn on the screen. So basically, the drops continue to fill up the canvas until all of it is blue! I need to clear the canvas after the drops have fallen.

Here are my draw and setup functions:

function draw() {
        drawBackground();

        for (var i=0; i< nOfDrops; i++)
        {
        ctx.drawImage (rainDrops[i].image, rainDrops[i].x, rainDrops[i].y); //The rain drop

        rainDrops[i].y += rainDrops[i].speed; //Set the falling speed
        if (rainDrops[i].y > 450) {  //Repeat the raindrop when it falls out of view
        rainDrops[i].y = -25 //Account for the image size
        rainDrops[i].x = Math.random() * 600;    //Make it appear randomly along the width    
        }

        }
    }

    function setup() {
        var canvas = document.getElementById('canvasRain');

        if (canvas.getContext) {
                ctx = canvas.getContext('2d');

                    imgBg = new Image();
            imgBg.src = "";
        setInterval(draw, 36);
        for (var i = 0; i < nOfDrops; i++) {
            var rainDr = new Object();
            rainDr["image"] =  new Image();
            rainDr.image.src = "rain.png";



            rainDr["x"] = Math.random() * 600;
            rainDr["y"] = Math.random() * 5;
            rainDr["speed"] = 3 + Math.random() * 5;
            rainDrops.push(rainDr);

            }

        }
    }

I'm pretty sure I'll need to clear the canvas in my draw function, but I'm not sure where exactly or how. Let me know if you need the full code or if you have any questions. Thanks.

1 Answers1

2

Use clearRect()

To clear the whole canvas:

ctx.clearRect(0, 0, canvas.width, canvas.height)

If you're wondering where to put it, you can just put it at the beginning of your draw function, so it'll clear before every frame.

Andrew
  • 763
  • 7
  • 21