Moving on a Vector

Moving between two points is handy, but sometimes you don’t have a point to move to, only a point to start from. In cases like this, it can be very useful to create a vector as a means to move your object.

A vector is a quantity in physics that has both magnitude and direction. For our purposes, the magnitude will be the speed value of the moving object, and the direction will be an angle value that the object will move upon.

The good news is that moving on a vector is very similar to moving between two points. In canvasApp(), we first set our speed value (magnitude). This is the number of pixels the object will move on every call to drawScreen(). We will set this to 5. We will also set the starting point (p1) for the object to 20,20:

var speed = 5;
var p1 = {x:20,y:20};

Now, we will set the angle value (direction) of movement for our object to 45 degrees. In mathematics, a flat, straight line usually represents the 0 angle, which means a vector with an angle of 45 degrees would be down and to the right on the canvas.

With our angle set, we now need to convert it to radians. Radians are a standard unit of angle measurement, and most mathematical calculations require you to convert an angle into radians before you can use it.

So why not just use radians and forget degrees altogether? Because it is much easier to understand movement in degrees when working with vectors and moving objects on a 2D surface. While a circle has 360 degrees, it has just about 6 radians, which ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.