简体   繁体   English

为什么我的动画无法通过setinterval清除

[英]Why my animation does not clear by setinterval

I have made a JS code where i make a Canvas and when the user clicks raindrops start falling in infinite loop. 我制作了一个JS代码,在其中制作了Canvas,当用户单击时,雨滴开始陷入无限循环。

enter code hereMy problem is that i make a "cloud" and i try to make it move through the canvas but instead it shows like it paints the whole path instead of moving. 我的问题是我制造了一个“云”,我试图使它在画布上移动,但相反,它显示的是绘制整个路径而不是移动。

My code is here: 我的代码在这里:

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

also the full code and project can be found in this CodePen 也可以在此CodePen中找到完整的代码和项目

Your for loop seems to be painting the entire cloud in an instant. 您的for循环似乎可以立即绘制整个云。 Instead you can increment its position over time instead of looping. 相反,您可以随着时间的推移增加其位置而不是循环。

So let's go from this: 因此,让我们从这里开始:

//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();
}

To this: 对此:

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

Live Demo 现场演示

If you want only 1 cloud, you don't need a for loop. 如果只需要1个云,则不需要for循环。 You can put a variable cloud outside of setInterval and change as rain in yPos. 您可以在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);

The code above will work and you can change it as you want. 上面的代码将起作用,您可以根据需要进行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM