清除画布

时间:2016-12-06 03:58:27

标签: javascript canvas

我正在尝试创建一个雨滴落下的画布,我唯一的问题是它们在屏幕上产生后没有清除。所以基本上,水滴继续填满画布直到所有它都是蓝色的!滴水落下后我需要清理画布。

以下是我的绘图和设置功能:

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);

            }

        }
    }

我很确定我需要在绘图功能中清除画布,但我不确定究竟在哪里或如何。如果您需要完整的代码或者您有任何疑问,请告诉我。感谢。

1 个答案:

答案 0 :(得分:2)

使用clearRect()

清除整个画布:

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

如果你想知道把它放在哪里,你可以把它放在绘图功能的开头,这样它就会在每一帧之前清除。

相关问题