The previous animation leaves a trail because the canvas is not cleared after each frame. To prevent this, we can use the clearRect
method to clear the canvas before drawing the next frame.
The context.clearRect(0, 0, canvas.width, canvas.height)
method clears the entire canvas, removing all previous drawings. This make sure that only the most recent rectangle is visible, creating a smooth animation effect.
By combining this with the xCoordinate
increment, the rectangle moves cleanly across the canvas without leaving behind any previous drawings.
Try out different values of xIncrement
to adjust the speed of the box. Starting in the next lesson, we will use a value of 5
to make the box move a bit more faster.