I am making an animation that infinitely deflates and inflates a ball. The code works but the problem is that its only looping once. Can someone tell me the issue. Thanks
my Code:https://codepen.io/coderkoji/pen/NWpJPqB?editors=0011
Notice that in the reference code of moving rectangle, the direction is adjusted. Based on this value, the position x is updated. The direction is used like a toggle, once set, you don’t have to change it until it reaches the left or right boundary edge.
In your code, the function deflate() is called only when the radius reaches 150 (provided the test is corrected to ===) and inflate is called only when the radius becomes 20. BUT what will happen when the radius is 21? Neither gets called.
Use integer values. The increment of a fractional values like 0.01 is very dangerous because of floating point precision error. If you increment by 0.01 or 0.1, you may never get the value to be exactly equal to 150 or 20. You can use >== or <== but in general it is always better to avoid floating point values for discrete counting.
You forgot to put ctx.beginPath() before calling the arc method.
=================
Here’s a sample solution. I put all the logic in the draw method, but you don’t have to.