Creating the Motion Trail

We'll cover the following...

The task ahead of us is pretty straightforward - especially given what we looked at in the previous section. What we are going to do now is take an object that moves around the canvas and give it a motion trail. You can create your own starting point for this, but if you want to closely follow along, continue with our usual example where we have a canvas element with an id of myCanvas. Inside that HTML document, add the following into the script tag:

  • HTML
  • JavaScript
javascript

Once you’ve added this code, go ahead and preview what you have in your browser. If everything worked out fine, you should see a circle moving from left to right. Right now, this circle shows no motion trail. We are going to fix that right up in the next couple of sections.

Understanding How Things Get Drawn

The first thing to do is to get an idea of how things are getting drawn to the screen. In our example, we have the update function that is part of the requestAnimationFrame loop. Inside it, the following code is responsible for drawing our circle:

Press + to interact
context.beginPath();
context.arc(xPos, yPos, 50, 0, 2 * Math.PI, true);
context.fillStyle = "#FF6A6A";
context.fill();

The xPos and yPos variables are responsible for figuring out where our circle is positioned. Just a few lines below our drawing code, we have the following:

Press + to interact
// update position
if (xPos > 600) {
xPos = -100;
}
xPos += 3;

This code is responsible for two things. The first is resetting the value of xPos if it gets larger than 600. The second is incrementing the value of xPos by 3 each time requestAnimationFrame calls our update function. In other words, around 60 times a second ideally.

You put all of this together, you can see why our circle moves the way it does. It starts off at -100, and makes its way right by 3 pixels each ...