Why isnt it looping

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

here’s the code that I am comparing it to:https://codepen.io/coderkoji/pen/XWMGJVX

There are several problems here.

1. The first one is this
`````` if(ball.radius = 150){ //MUST BE ===
deflate();
inflate()
}
``````

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.

1. 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.

2. 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.

Spoiler
``````const canvas = document.getElementById("my-canvas");
const ctx = canvas.getContext("2d");
canvas.height = 500;
canvas.width = 800;

const ball = {
x: 200,
y: 200,
color: "green",
shrink: false
}

const draw = ball => {
// console.log(ball.radius + '  ' + ball.shrink)
if (ball.shrink) {
} else {
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = ball.color
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2)
ctx.fill()

ball.shrink = true;
ball.color = 'red';
} else if (ball.radius === 20){
ball.shrink = false;
ball.color ='green';
}
}

const growCircle = () => {

draw(ball)

requestAnimationFrame(growCircle);
}

growCircle()
``````

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.