Step 5

Let's make animation! Add the following snippet to the end of main.js file:

let x = canvas.width / 2;
let y = canvas.height - 30;
const dx = 2;
const dy = -2;

function draw() {
  ctx.beginPath();
  ctx.rect(x, y, 10, 10);
  ctx.fillStyle = "#0095DD";
  ctx.fill();
  ctx.closePath();
  x += dx;
  y += dy;

  window.requestAnimationFrame(draw);
}

draw();

The window.requestAnimationFrame(draw) tells the browser to call the draw function repeatedly (60 times per second).

Each time the draw function is called, it paints a blue square to the canvas and updates its coordinates. Thus, it appears as if the square is moving across the canvas (leaving a trail behind):

The apparent trail exists because we are painting a new square on every frame without clearing the canvas.

Add the following statement as the first line inside the draw function to clear the canvas before painting a new frame.

ctx.clearRect(0, 0, canvas.width, canvas.height);

The moving blue square does not leave a trail anymore! Instead, it moves across the canvas until it eventually exits it! Moreover, the red square has disappeared! This is because the red square was drawn outside of the draw function. It gets wiped out as soon as draw is called. This action happens so fast that you don't see it on the screen.