为什么我的动画没有通过设置间隔清除



我制作了一个JS代码,我在其中制作了一个Canvas,当用户点击雨滴时,雨滴开始无限循环。

在此处输入代码我的问题是我制作了一个"云",我试图让它在画布上移动,但它显示它就像它绘制了整个路径而不是移动。

我的代码在这里:

setInterval(function () {
//cear the canvas
ctx.clearRect(0, 0, c.width, c.height);
//sxediazoume to fontou
ctx.fillStyle = "rgb(204, 247, 255)";
ctx.fillRect(0, 0, c.width, c.height);
//grass
ctx.fillStyle = "green";
ctx.fillRect(0, c.height-20, c.width, c.height);
//house
ctx.fillStyle = "#f4e6be";
ctx.fillRect(50, c.height-20, 100, -80);
ctx.fillStyle = "black";
if (makeRain == 1) {
//moving the Cloud
for ( var i=0 ; i< c.width/2 ; i+=5) {
ctx.fillStyle = "#a1a4a8";
ctx.beginPath();
ctx.arc(i, i, 40, 0*Math.PI, 2*Math.PI);
ctx.fill();
}
}, 10);

完整的代码和项目也可以在这个代码笔中找到

您的 for 循环似乎在瞬间绘制了整个云。相反,您可以随着时间的推移增加其位置,而不是循环。

因此,让我们从这里开始:

//moving the Cloud
for ( var i=0 ; i< c.width/2 ; i+=5) {
ctx.fillStyle = "#a1a4a8";
ctx.beginPath();
ctx.arc(i, i, 40, 0*Math.PI, 2*Math.PI);
ctx.fill();
}

对此:

var cloudPos = 0; // somewhere outside the interval
//metakinoude ta Clouds
if (cloudPos >c.width){
cloudPos = 0;
}
ctx.fillStyle = "#a1a4a8";
ctx.beginPath();
ctx.arc(-20+cloudPos, 100, 40, 0*Math.PI, 2*Math.PI);
ctx.fill();
cloudPos+= 5; // increment position

现场演示

如果你只需要 1 个云,你不需要 for 循环。您可以在 setInterval 之外放置一个可变云,并在 yPos 中更改为雨。

var cloud = 0;
setInterval(function () {
//The code for other things
// ...
//
if (makeRain == 1) {
cloud += 5;
cloud %= c.height;
ctx.fillStyle = "#a1a4a8";
ctx.beginPath();
ctx.arc(-20+cloud, 100, 40, 0*Math.PI, 2*Math.PI);
ctx.fill();
}
}, 10);

上面的代码将起作用,您可以根据需要进行更改。

最新更新