Html5 canvas animation not working properly

I am trying to create an animation in a canvas. The first time it worked fine, but when a new element was added via setTimeout, all element speeds increase. Can someone tell me why this speed is increasing. Script Link

var canvas = $("#canvas")[0], context = canvas.getContext("2d"), bloons = {}, bloonIndex = 0; var c_wdh = 360, c_hgt = 540; function createBloon(x, y) { this.x = x; this.y = y; this.vx = 1, this.vy = 3; bloonIndex++; bloons[bloonIndex] = this; this.id = bloonIndex; } createBloon.prototype.drawImage = function() { this.y -= this.vy; context.fillStyle = "#FF0000"; context.fillRect(this.x, this.y, 50, 50); if(this.y <= -120){ delete bloons[this.id]; } }; var nob = 0; var i = 1; var rendorBloon = setInterval(function(){ bloons[i] = new createBloon(Math.random() * c_wdh, c_hgt); var animate = setInterval(function () { context.clearRect(0, 0, c_wdh, c_hgt); for (var i in bloons){ bloons[i].drawImage(); } }, 30); i++; nob++; if(nob >= 10){ clearInterval(rendorBloon); } }, 1000); 
+5
source share
1 answer

I will try to explain to you why the animation speeds up. Each time rendorBloon setInterval is rendorBloon , a new setInterval is created. The following steps explain the process:

1 - First run rendorBloon setInterval (1 second):

  1 setInterval is created. 1 setInterval is running, it will run every 30 milliseconds 

2 - Second run of rendorBloon setInterval (2 seconds):

  1 setInterval is created. 2 setInterval are running, they will run every 30 milliseconds 

3 - Third run rendorBloon setInterval (3 seconds):

  1 setInterval is created. 3 setInterval are running, they will run every 30 milliseconds 

4 -... Lasts 10 times

In each rendorBloon execution, a new setInterval is created, and each setInterval executes the drawImage method, which moves the image 3 pixels higher. When you clear rendorBloon setInterval, you will have 10 functions trying to move each field. Result: boxes move 3 pixels with the first iteration, 6 pixels with the second, 9 pixels with the third and continue.

I created a new jsfiddle modifying some things:

1 - Separate the two setIntervals .

2 - Move the animation logic to the animation function.

3 - Move the removal of the boxes to the animation function.

4 - Create the drawImage method directly in the createBloon function, avoiding prototype .

5 - Clear animate setInterval when the animation is over.

6 - Make sure all cells are selected inside the canvas using c_wdh - width of the boxes for random values.

Here you have the new jsfiddle .

0
source

Source: https://habr.com/ru/post/1239621/


All Articles