Let us begin by animating a box moving horizontally using the setInterval
method we have already learned.
The setInterval
function makes sure that the drawBox
function is called repeatedly at this interval. Inside drawBox
, the xCoordinate
is incremented by the value of xIncrement
, and the box is redrawn every 16 milliseconds.
We use clearInterval
within a conditional check to stop drawing new rectangles once the right edge of the current rectangle exceeds the canvas's width. Subtracting boxWidth
from canvas.width
makes sure that the rectangle remains fully visible within the canvas.
However, since we are not clearing the previous boxes, each new frame leaves a trail of boxes.