Move the Points

When we defined the animation we are creating, we said that points were to move in a fixed direction with constant speed. We can use a 2D vector to represent both the direction and the speed of a point.

A vector has a horizontal (x) and a vertical (y) component, and a magnitude. The two components determine the direction/where the point is looking towards. It’s usually described by an angle (degrees or radians). The magnitude is the length of the vector, or in our case the speed of the point, which determines how fast the point is moving in the direction it is “facing” at a specific point in time.

We know we can use degrees and radians when working with direction, but what do we use for speed? As an example, we can say that a car is moving at 60 miles per hour, and a person is walking at 1.4 meters per second. There’s a simple formula we all learned in school that defines speed as equal to distance divided by time. What are the distance and time we are working with?

The screen that you are looking at right now is made of pixels, and we can use the number of pixels to determine its logical display size. That’s the unit we also used when defining the width and height of the <canvas> : we set both to be 400px. As points will be moving on the canvas as well as on the screen, we can use pixels as the unit for our distance.

And, as we mentioned above, the browser will let us process our animation every ~16ms. We will refer to that as a frame duration, and that will be our time unit. That leaves us with speed being pixels per frame duration.

The actual values can be any number we’d like. We can experiment with different values to determine what works best.

Now, back to moving the points. With the help of basic trigonometry, we can calculate the point’s displacement given its direction and speed with two equations:

x = speed * cos(direction)

y = speed * sin(direction)

If we add the displacement to the current position, we will have the point’s next position.

Enough math, let’s code.

We created a function called movePoint that given a point object, now with two new properties s and d , updates the point’s position. This function will be called as part of the animation loop.

We also need to change the point creation to set the two new properties.

We set d to be a random number between 0 and 360 degrees, so points will move in random directions, and s to be 1 px/fd.

Putting together all we have so far, we should have moving points!

See it live below: