Previously, we used a conditional check with requestAnimationFrame(drawBox)
to stop the animation once the right edge of the box exceeded the canvas's width. Now, we want to make the box bounce back when it hits the edge of the canvas. This requires a different approach.
In this code, we continuously run requestAnimationFrame(drawBox)
to make sure the animation never stops. We have also added a conditional check to handle the bouncing behavior.
For the right edge, we check whether the box's current xCoordinate
plus its width exceeds the canvas's width. For the left edge, we check whether the xCoordinate
falls below 0. If either condition is met, we reverse the xIncrement
value, making the box move in the opposite direction.
By using this logic, the box appears to bounce back from the canvas edges, creating a seamless back-and-forth animation.